home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
MacFormat 1994 November
/
macformat-018.iso
/
Utility Spectacular
/
Developer
/
macgambit-20-compiler-src-p1
/
Online Help
< prev
next >
Encoding:
Amiga
Atari
Commodore
DOS
FM Towns/JPY
Macintosh
Macintosh JP
NeXTSTEP
RISC OS/Acorn
UTF-8
Wrap
Text File
|
1994-07-26
|
172.8 KB
|
4,184 lines
|
[
TEXT/????
]
MacGambit
A. Introduction 0
- 0
B. Using the online help 1247
- 0
C. User interface 2595
C.1. Interacting with the interpreter 2617
C.2. Basic editing 7797
C.3. Special keys 8688
C.4. Arrow keys 9194
C.5. Emacs commands 10642
C.6. Small keyboard emacs mode 11774
C.7. Mouse 12888
C.8. Scrolling 13505
C.9. Editor limitations 13720
- 0
D. Language extensions 13924
D.1. Concurrent evaluation 14059
D.2. Semaphores 15302
D.3. Queues 15838
D.4. Weak Pairs 16665
D.5. Ports 17502
D.6. Symbols 20082
D.7. Evaluation 20862
D.8. Tracing 22400
D.9. Miscellaneous 22798
D.10. Graphics 23861
D.11. Text windows 24963
D.12. Toolbox interface 25444
R4RS
1. Overview of Scheme 29391
1.1. Semantics 29417
1.2. Syntax 32799
1.3. Notation and terminology 33400
1.3.1. Essential and non-essential features 33434
1.3.2. Error situations and unspecified behavior 34047
1.3.3. Entry format 35651
1.3.4. Evaluation examples 38602
1.3.5. Naming conventions 39121
- 0
2. Lexical conventions 39803
2.1. Identifiers 40191
2.2. Whitespace and comments 42089
2.3. Other notations 43131
- 0
3. Basic concepts 44760
3.1. Variables and regions 44782
3.2. True and false 46700
3.3. External representations 47110
3.4. Disjointness of types 49267
3.5. Storage model 49625
- 0
4. Expressions 51311
4.1. Primitive expression types 51881
4.1.1. Variable references 51917
4.1.2. Literal expressions 52322
4.1.3. Procedure calls 53856
4.1.4. Lambda expressions 55381
4.1.5. Conditionals 57790
4.1.6. Assignments 58593
4.2. Derived expression types 59112
4.2.1. Conditionals 59323
4.2.2. Binding constructs 63696
4.2.3. Sequencing 67469
4.2.4. Iteration 68084
4.2.5. Delayed evaluation 71120
4.2.6. Quasiquotation 71633
- 0
5. Program structure 74339
5.1. Programs 74364
5.2. Definitions 75249
5.2.1. Top level definitions 76318
5.2.2. Internal definitions 77229
- 0
6. Standard procedures 78431
6.1. Booleans 78923
6.2. Equivalence predicates 80929
6.3. Pairs and lists 89220
6.4. Symbols 100276
6.5. Numbers 104239
6.5.1. Numerical types 105260
6.5.2. Exactness 106926
6.5.3. Implementation restrictions 108495
6.5.4. Syntax of numerical constants 112972
6.5.5. Numerical operations 114811
6.5.6. Numerical input and output 130979
6.6. Characters 134169
6.7. Strings 139477
6.8. Vectors 145492
6.9. Control features 149072
6.10. Input and output 159159
6.10.1. Ports 159186
6.10.2. Input 162997
6.10.3. Output 166744
6.10.4. System interface 168994
- 0
7. Formal syntax and semantics 170485
A-B
abs 121317
acos 126325
and b62459
angle 128861
append 96331
apply 149743
asin 126325
assoc 98905
assq 98905
assv 98905
atan 126325
- 0
begin b67469
boolean? 80637
C
c...r 94681
call-with-current-continuation 155293
call-with-input-file 159401
call-with-output-file 159401
car 93467
case b61015
cdr 93828
ceiling 124061
char->integer 138260
char-alphabetic? 137387
char-ci<=? 136667
char-ci<? 136667
char-ci=? 136667
char-ci>=? 136667
char-ci>? 136667
char-downcase 139094
char-lower-case? 137387
char-numeric? 137387
char-ready? 165775
char-upcase 139094
char-upper-case? 137387
char-whitespace? 137387
char<=? 135595
char<? 135595
char=? 135595
char>=? 135595
char>? 135595
char? 135450
clear-graphics i23880
clear-point i23880
close-input-port 162622
close-output-port 162622
compile-file i21236
complex? 115417
cond b59323
cons 92972
cos 126325
current-input-port 160923
current-output-port 160923
D-F
define b75249
delay b71120
denominator 123525
display 167307
do b68084
draw-line-to i23880
draw-point i23880
- 0
else b59323
eof-object? 165453
eq? 86628
equal? 88456
eqv? 81368
error i22821
eval i20882
even? 118636
exact->inexact 130105
exact? 117297
exit i23342
exp 126325
expt 128675
- 0
floor 124061
for-each 151309
force 151915
future ib14059
G-L
gcd 123005
gensym i20099
get i20412
get-output-string i17517
graphics-text i23880
- 0
if b57790
imag-part 128861
inexact->exact 130105
inexact? 117297
input-port? 160668
integer->char 138260
integer? 115417
- 0
lambda b55381
lcm 123005
length 96095
let b63696
let* b65198
letrec b65878
list 95872
list->string 144753
list->vector 148383
list-ref 97599
list-tail 97282
list? 95436
load 169191
log 126325
M-N
magnitude 128861
make-polar 128861
make-queue i15854
make-rectangular 128861
make-semaphore i15322
make-string 141132
make-vector 146787
map 150408
max 119142
member 97915
memq 97915
memv 97915
min 119142
modulo 121486
- 0
negative? 118636
newline 168184
not 80199
null? 95288
number->string 131017
number? 115417
numerator 123525
O-R
odd? 118636
open-input-file 162026
open-input-string i17517
open-output-file 162276
open-output-string i17517
open-text-window i24986
or b63065
output-port? 160668
- 0
pair? 92654
peek-char 164546
position-pen i23880
positive? 118636
pp i19384
pretty-print i19384
procedure? 149263
put i20412
- 0
quasiquote b71633
queue-get! i15854
queue-put! i15854
quote b52322
quotient 121486
- 0
rational? 115417
rationalize 125529
read 163015
read-char 164101
real-part 128861
real? 115417
remainder 121486
reverse 96986
round 124061
runtime i23459
S
semaphore-signal i15322
semaphore-wait i15322
set! b58593
set-car! 94153
set-cdr! 94507
set-gc-report i23607
sin 126325
sqrt 128454
string 141492
string->list 144753
string->number 132602
string->symbol 103276
string-append 144572
string-ci<=? 142925
string-ci<? 142925
string-ci=? 142462
string-ci>=? 142925
string-ci>? 142925
string-copy 145188
string-fill! 145323
string-length 141637
string-ref 141777
string-set! 141975
string<=? 142925
string<? 142925
string=? 142462
string>=? 142925
string>? 142925
string? 140990
substring 144178
symbol->string 102205
symbol? 101815
T-Z
tan 126325
touch i15083
trace ib22400
transcript-off 169825
transcript-on 169825
truncate 124061
- 0
untrace ib22400
- 0
vector 147136
vector->list 148383
vector-fill! 148892
vector-length 147368
vector-ref 147495
vector-set! 147905
vector? 146645
- 0
weak-car i16685
weak-cdr i16685
weak-cons i16685
weak-pair? i16685
weak-set-car! i16685
weak-set-cdr! i16685
with-input-from-file 161130
with-input-from-port i19052
with-input-from-string i18419
with-output-to-file 161130
with-output-to-port i19052
with-output-to-string i18419
write 166763
write-char 168588
- 0
zero? 118636
Others
' b52322
* 119958
+ 119958
, b71633
– 120392
/ 120392
; b42089
< 117598
<= 117598
= 117598
=> b59323
> 117598
>= 117598
` b71633
ÛA. Introductionˇ
MacGambit is a full implementation of Scheme that conforms to the IEEE-Scheme standard
(IEEE P1178) and to the Revised˝4ˇ Report on Scheme (R4RS). The system supports the whole
numeric tower (i.e. integer, rational, real and complex numbers). It also has several
extensions to the standards including: weak pairs, string ports, property lists, pretty
printer, debugger, compiler and multitasking. Macintosh specific features include: a Scheme
interface to several Toolbox routines, a drawing window for simple graphics, an online help
system and a Scheme oriented editor with an emacs compatibility mode.
MacGambit runs on all Macintosh computers but requires at least 2 MB of RAM and System 6
or later. When the program is launched, it grabs most of the memory for its heap and leaves
the rest for the Mac's own needs. When running Multifinder or System 7, it is possible to
limit the amount of memory allocated by setting the "application memory size" (with the
finder's Ícmd-Iˇ command).
The latest version of MacGambit can be obtained through the INTERNET from the following
anonymous FTP site:
Í trex.iro.umontreal.ca:pub/gambitˇ
Email concerning MacGambit should be sent to:
Í gambit@trex.iro.umontreal.caˇ
ÛB. Using the online helpˇ
The online help contains two documents. The first document (MacGambit) contains
information that is specific to MacGambit. The second document (R4RS) is a definition of the
Scheme programming language. The first two menus of the online help window are the
respective table of contents of these documents. The remaining menus are an alphabetic
index of the procedures and special forms available. Procedures are in plain face, special
forms are in bold face and MacGambit specific extensions are in italic.
Navigating through the documentation is done either by selecting a topic from one of the help
window's menus or by calling the procedure Íhelpˇ. When given the name of a procedure or
special form (as a string or symbol), Íhelpˇ will move the help window to the appropriate
part of the documentation.
The main chapters of R4RS have been reproduced as faithfully as possible including the
formatting conventions. However a few sections were omitted for space reasons: the
summary, introduction, chapter 7 and appendices. We thank the editors of R4RS, William
Clinger and Jonathan Rees, for making the report publicly available. The complete R4RS
document can be obtained from the following anonymous FTP sites:
Í nexus.yorku.ca:pub/scheme/doc/r4rs.ps.Zˇ
Í altdorf.ai.mit.edu:pub/scheme-reports/r4rs.psˇ
ÛC. User interfaceˇ
ÛC.1. Interacting with the interpreterˇ
Interaction with the interpreter's read-eval-print (REP) loop is done inside the "interaction"
window. The content of the interaction window can be edited at will by the user. This window
also acts as the default output port (and input port). Consequently, the interpreter sends its
output to the interaction window. User input and system output are displayed with different
fonts. By default, user input is in bold face (but this and other attributes of the window can
be changed with the "Styles..." item in the Edit menu).
Normally, the user types an expression and then "sends" it to the interpreter to be
evaluated. The result of the evaluation is then output to the interaction window. The
preferred way of evaluating an expression is to place the insertion point (caret) immediately
after the expression to evaluate and then typing Ícmd-returnˇ (i.e. press the Íreturnˇ key
while pressing the Ícommandˇ key). An alternative method is to use the Íenterˇ key. When
Íenterˇ is pressed, the sequence of "user input" characters immediately preceding the
insertion point are sent to the interpreter. Because it doesn't check for a properly formed
expression, the Íenterˇ key is useful for programs doing text oriented input. Arbitrary text
can also be sent to the interpreter by selecting the text before typing Ícmd-returnˇ or
Íenterˇ.
These interaction mechanisms also work from windows associated to files. However, the
result of evaluation is always displayed in the interaction window.
As opposed to most other Lisp systems, MacGambit combines the standard REP loop functions
with those of the debugger. In a sense, the user is always interacting with the debugger.
When an evaluation error is detected by the interpreter, a message describing the error is
displayed and a REP loop of a higher level is started (the topmost REP loop is numbered 0).
This REP loop is positionned in the context of the error so that the user can determine the
cause of the error and possibly repair the problem and resume the evaluation as though no
error had occured.
At all times it is possible to examine the frames in the REP loop's continuation (i.e. the call
stack). This is useful to locate the source of an error. Expressions typed in to the REP loop
are evaluated in the context of the frame currently being examined. This is useful to check
the bindings of variables and mutate them (check the examples for details). Special
commands accepted by a REP loop are:
Ícmd-Rˇ -- Returns from an error or interrupt (the user is prompted for the return value).
This value is ignored when returning from an interrupt.
Ícmd-Dˇ -- Returns to the previous REP loop (also acts as end-of-file).
Ícmd-Tˇ -- Returns to the top-most REP loop.
Ícmd-?ˇ -- Gives summary of commands.
Ícmd-+ˇ -- Moves to next frame of the continuation and displays it in the same format as
Ícmd-Bˇ.
Ícmd--ˇ -- Moves to previous frame of the continuation and displays it in the same format as
Ícmd-Bˇ.
Ícmd-Bˇ -- Displays a summary of each frame in the continuation starting with the current
frame. There are 3 columns. The first is the frame number. The second is the procedure that
created the frame (and where control will return when this frame is resumed). The last
column, if it is present, is the expression whose value is being computed. A frame created
by a compiled procedure has a third column only if the procedure was compiled with the
DEBUG option.
Ícmd-Lˇ -- Lists all non-global variables accessible from the current frame.
Ícmd-Iˇ -- Pretty prints the procedure that created the current frame.
Ícmd-Yˇ -- Displays subproblem expression for the current frame.
Ícmd-.ˇ -- This can be typed at any moment to interrupt the current computation. A new REP
loop is started.
Ícmd-Jˇ -- Loads a file.
Ícmd-Kˇ -- Compiles a file.
Here is a transcript of a typical interaction with MacGambit (comments are marked with
";;;" and user input is in bold):
ÌMacGambit (v2.0)
Ì
Ì: Í(define (f x y) (/ (+ x y) 2))Ì
Ìf
Ì
Ì: Í(let ((a 10) (b 20))
Í (* (f a 'b) (f a 100)))Ì ;;; we meant b not 'b
Ì*** ERROR -- NUMBER expected
Ì(+ 10 'b)
Ì
Ì1: ;;; typed Ícmd-BÌ to get backtrace
Ì0 f (+ x y)
Ì-1 (top level) (f a 'b)
Ì-2 (top level) (let ((a 10) (b 20)) (* (f a 'b)...
Ì-3 ##dynamic-env-bind
Ì-4 ##read-eval-print
Ì-5 ##dynamic-env-bind
Ì-6 ###_kernel.startup
Ì
Ì1: ;;; typed Ícmd-IÌ to get the procedure that caused the error
Ì#[procedure f] =
Ì(lambda (x y) (/ (+ x y) 2))
Ì
Ì1: ;;; typed Ícmd-LÌ to get the variables accessible here
Ìx = 10
Ìy = b
Ì
Ì1: ;;; typed Ícmd--Ì to move to the previous subproblem
Ì-1 (top level) (f a 'b)
Ì
Ì1-1: ;;; typed Ícmd-LÌ
Ìa = 10
Ìb = 20
Ì
Ì1-1: ;;; typed Ícmd-+Ì
Ì0 f (+ x y)
Ì
Ì1: ;;; typed Ícmd-RÌ to return from error
ÌReturn value: Í(+ x 20)Ì
Ì825
Ì
Ì: ;;; typed Ícmd-QÌ
Ìˇ
The file "init.scm" can be used to customize the interpreter. It is loaded just before the
initial REP loop is entered. The file is first searched in the folder containing the document
being opened and then in the folder containing the interpreter.
ÛC.2. Basic editingˇ
It is assumed that you are familiar with standard Macintosh editing techniques. If not, you
should consult your Getting Started disks and Macintosh users' manuals.
On all keyboards the following keys are defined:
Í delete -ˇ erase character before cursor position
Í tab -ˇ indent current line
Í return -ˇ insert a new line and move to the left margin (and then
Í ˇ do a Ítabˇ if autoindent is selected for the window)
Ícmd-return -ˇ send the expression preceding the insertion point
Í enter -ˇ send the user input preceding the insertion point
Printable characters which are legal in Scheme programs are simply inserted into the buffer
(these are characters in the range of 32 through 126 in the ASCII table). Other characters
are simply discarded. However, you can paste arbitrary characters from another application
or desk accessory.
ÛC.3. Special keysˇ
On extended keyboards the following special keys are supported:
Í F1 - F4 -ˇ equivalent to Undo, Cut, Copy and Paste
Í F5 - F15 -ˇ function keys (not used)
Í del> -ˇ erase character after the insertion point
Í home -ˇ scroll text to the top of the edit buffer
Í end -ˇ scroll text to the bottom of the edit buffer
Í page up -ˇ scroll text up a page
Í page down -ˇ scroll text down a page
Note that these last four do not move the insertion point, just scroll.
ÛC.4. Arrow keysˇ
Arrow keys (when available) move the insertion point in the corresponding direction:
Í left -ˇ move cursor to the left one character
Í right -ˇ move cursor to the right one character
Í up -ˇ move cursor up one line
Í down -ˇ move cursor down one line
Arrow keys can be modified with the Íshiftˇ, Íoptionˇ, and Ícommandˇ keys.
The Íshiftˇ key may be used to extend the text selection per Apple standards. Each selection
has an anchor end and an active end. Generally, the active end is the last end you moved, the
anchor end doesn't move. When the Íshiftˇ key is held down, the selection's active end is
moved by the arrow keys.
The Íoptionˇ key may be used with the arrow keys to move the insertion point left or right
by word, or up or down by page. ÍShiftˇ and Íoptionˇ together may be used to move the
active end of the selection left or right by words, or up or down by pages.
The Ícommandˇ key may be used with the arrow keys to move the insertion point left or right
to the beginning or end of the line, or up or down to the beginning or end of the text. ÍShiftˇ
and Ícommandˇ together may be used to move the active end of the selection to start or end of
the line or text.
When Íshiftˇ, Íoptionˇ, and Ícommandˇ are held down together, the up or left arrow will make
the beginning of the selection the active end, and the down or right arrow will make the end
of the selection the active end.
ÛC.5. Emacs commandsˇ
A small subset of Emacs compatible command keys are supported by the editor. Some of
these commands make use of the Ícontrolˇ key. The Ícontrolˇ key does not exist on small
keyboards but it can be simulated by using the Small Keyboard mode (see below).
The following table lists the Emacs compatible command keys using the following
abbreviations: ÍCˇ = Ícontrolˇ key, ÍMˇ = Íoptionˇ key (Emacs' "meta" key).
Commands which move the insertion point:
Í C-f -ˇ forward character
Í C-M-f -ˇ forward S-expression
Í C-b -ˇ backward character
Í C-M-b -ˇ backward S-expression
Í C-a -ˇ beginning of line
Í C-M-a -ˇ beginning of S-expression
Í C-m -ˇ select enclosing S-expression
Í C-M-m -ˇ select enclosing S-expression
Í C-e -ˇ end of line
Í C-M-e -ˇ end of S-expression
Í C-p -ˇ previous line
Í C-n -ˇ next line
Commands which modify the buffer:
Í C-d -ˇ delete forward (same as Ídel>ˇ key)
Í C-del> -ˇ delete to end of line
Í C-k -ˇ same as ÍC-del>ˇ
Í C-o -ˇ open line
Other commands: Í M-return -ˇ same as Ícmd-returnˇ
ÛC.6. Small keyboard emacs modeˇ
To use Emacs commands on small keyboards without a Ícontrolˇ key, the menu item "Small
Keyboard" may be checked in the Edit menu. When it is checked, all keyboard events are
interpreted as follows:
• the Íoptionˇ key acts as the Ícontrolˇ key
• pressing the Íoptionˇ and Ícommandˇ keys simultaneously acts the same as the
Ícontrol-optionˇ combination.
The original keyboard interpretation is restored by unchecking Small Keyboard mode.
Note that Small Keyboard mode has no effect on other events (e.g., mouse modifiers remain
as documented earlier).
There is one quirk in small keyboard mode: since Íoption-nˇ and Íoption-eˇ are normally
"dead keys," MacGambit requires a special keyboard mapping resource (KMAP). For System
6 users, nothing special needs to be done - the KMAP resource is included in the MacGambit
application. For System 7 users, you must drag the file "U.S. Live" onto your System file for
the MacGambit keyboard mapping to take effect. MacGambit's keyboard mapping will only
affect MacGambit, the dead keys will continue to work in other applications.
ÛC.7. Mouseˇ
The editing action is specified by the number of mouse button clicks:
Í single -ˇ position insertion point
Í double -ˇ select word
Í triple -ˇ select line
Dragging after one of these clicks extends the selection by character, word, or line
respectively; the anchor point is the original click position, the active end is the other end of
the selection. After a click-drag, the active end can be moved with Íshiftˇ clicks or Íshiftˇ
arrow keys. The anchor and active ends of the selection can be swapped with
Íoption+shift+clickˇ, or Íoption+shift+commandˇ up/down or left/right arrow keys.
ÛC.8. Scrollingˇ
Holding down Ícommandˇ, Íshiftˇ, Íoptionˇ, and Ícontrolˇ keys speeds up scrolling when
mousing in the arrows of the scroll bar. The more keys you hold down the faster it scrolls
(exponentially).
ÛC.9. Editor limitationsˇ
The text size is limited by memory space. There is a limit of 32,000 lines (not characters)
per window. The editor has been used with files several hundred kilobytes in size.
ÛD. Language extensionsˇ
This chapter gives a list of the procedures and special forms supported by MacGambit that
are not in R4RS.
ÛD.1. Concurrent evaluationˇ
Í(future˘ ˇ<expression>Í) ˇsyntax
The Ífutureˇ construct is used to implement ˘concurrent evaluationˇ. Í(future ˇ<expression>Í)ˇ
creates a task to evaluate <expression> concurrently with the rest of the program (the
continuation). The value returned by Ífutureˇ represents the value eventually computed for
<expression>. If a task tries to use the value in a strict operation (such as Í+ˇ and Ícarˇ, but not
Íconsˇ), the task is suspended until the value is known.
Í (define (f n) (expt 3 n))
Í
Í (let ((x (future (f 101))))
Í (let ((y (f 100)))
Í (/ x y))) ==> 3
Í
Í (let ((a 1))
Í (future
Í (set! a (/ (f 101) (f 100))))
Í a) ==> 1 ˘orÍ 3
Í
Í (define count 0)
Í (define (inc) (set! count (+ count 1)))
Í (define x (future (let loop () (inc) (loop))))
Í count ==> 1014
Í count ==> 3055 ˘etc.ˇ
Í(touch˘ objÍ) ˇprocedure
ÍTouchˇ is a strict operation that returns its argument.
Í (touch 5) ==> 5
Í (touch (future 5)) ==> 5ˇ
ÛD.2. Semaphoresˇ
Í(make-semaphore) ˇprocedure
Í(semaphore-wait˘ semaphoreÍ) ˇprocedure
Í(semaphore-signal˘ semaphoreÍ) ˇprocedure
These procedures implement the semaphore data type. Semaphores are generally used to
enforce mutual exclusion. ÍSemaphore-waitˇ locks the semaphore and Ísemaphore-signalˇ
unlocks it. A task trying to lock a semaphore with Ísemaphore-waitˇ is suspended until the
semaphore is unlocked.
ÛD.3. Queuesˇ
Í(make-queue) ˇprocedure
Í(queue-put!˘ queue objÍ) ˇprocedure
Í(queue-get!˘ queueÍ) ˇprocedure
These procedures implement the queue data type. A queue is a sequence of items. Items are
added to the tail of the sequence by Íqueue-put!ˇ. ÍQueue-get!ˇ removes the next element at
the head of the sequence. If the sequence is empty, Íqueue-get!ˇ returns Í#fˇ. Otherwise a
single element list containing the item is returned. ÍQueue-put!ˇ and Íqueue-get!ˇ are
atomic operations.
Í (define q (make-queue))
Í (queue-put! q 1)
Í (queue-put! q 2)
Í (queue-get! q) ==> (1)
Í (queue-get! q) ==> (2)
Í (queue-get! q) ==> #fˇ
ÛD.4. Weak Pairsˇ
Í(weak-pair?˘ objÍ) ˇprocedure
Í(weak-cons˘ obj¯1˘ obj¯2Í) ˇprocedure
Í(weak-car˘ pairÍ) ˇprocedure
Í(weak-cdr˘ pairÍ) ˇprocedure
Í(weak-set-car!˘ pair objÍ) ˇprocedure
Í(weak-set-cdr!˘ pair objÍ) ˇprocedure
These procedures are the corresponding pair operations for the "weak pair" data type. Weak
pairs are similar to normal pairs except that the object in the car field is "weakly linked" as
far as garbage collection is concerned. The car field will be set to Í#fˇ by the garbage
collector if it finds that there are only weak links to the object.
ÛD.5. Portsˇ
Í(open-input-string˘ stringÍ) ˇprocedure
Í(open-output-string) ˇprocedure
Í(get-output-string˘ portÍ) ˇprocedure
These procedures implement string ports. String ports can be used like normal ports. The
characters are obtained from (or sent to) a string instead of a file. An output string port
accumulates the characters written to the port. The procedure Íget-output-stringˇ
extracts the sequence of characters accumulated up to that point and returns them as a
string.
Í (define ip (open-input-string "(1 2)foo"))
Í (define op (open-output-string))
Í (read ip) ==> (1 2)
Í (read ip) ==> foo
Í (read ip) ==> #[eof]
Í (write 'bar op)
Í (write '(a b) op)
Í (get-output-string op) ==> "bar(a b)"ˇ
Í(with-input-from-string˘ string thunkÍ) ˇprocedure
Í(with-output-to-string˘ thunkÍ) ˇprocedure
The procedure Íwith-input-from-stringˇ is similar to Íwith-input-from-fileˇ except
that the characters are obtained from a string. The procedure Íwith-output-to-stringˇ
calls the thunk and returns a string containing all characters output to the current output
port.
Í (with-input-from-string
Í "a string"
Í (lambda ()
Í (read-char))) ==> #\a
Í
Í (with-output-to-string
Í (lambda ()
Í (write (cons 1 2)))) ==> "(1 . 2)"ˇ
Í(with-input-from-port˘ port thunkÍ) ˇprocedure
Í(with-output-to-port˘ port thunkÍ) ˇprocedure
These procedures are respectively similar to Íwith-input-from-fileˇ and
Íwith-output-to-fileˇ. The difference is that the first argument is a port instead of a file
name.
Í(pretty-print˘ objÍ) ˇprocedure
Í(pretty-print˘ obj portÍ) ˇprocedure
Í(pretty-print˘ obj port kÍ) ˇprocedure
Í(pp˘ objÍ) ˇprocedure
Í(pp˘ obj portÍ) ˇprocedure
Í(pp˘ obj port kÍ) ˇprocedure
ÍPretty-printˇ and Íppˇ are similar to Íwriteˇ except that the result is nicely formatted. The
argument ˘kˇ specifies the width of the page. If ˘objˇ is a procedure created by the interpreter,
Íppˇ will display its definition.
ÛD.6. Symbolsˇ
Í(gensym) ˇprocedure
Í(gensym˘ prefixÍ) ˇprocedure
ÍGensymˇ returns a new "uninterned" symbol. ˘Prefixˇ is used as a prefix to the generated
name. ˘Prefixˇ is either a string or symbol and it defaults to "g".
Í(get˘ symbol propÍ) ˇprocedure
Í(put˘ symbol prop objÍ) ˇprocedure
ÍGetˇ and Íputˇ access the property list of symbols. ÍPutˇ associates the value ˘objˇ with the
property ˘propˇ of the symbol. ÍGetˇ extracts the value associated with the property ˘propˇ of
the symbol. ÍGetˇ returns Í#fˇ if ˘propˇ has not been set for the symbol. ˘Propˇ can be any object.
ÛD.7. Evaluationˇ
Í(eval˘ objÍ) ˇprocedure
ÍEvalˇ's argument is a datum representing an expression. ÍEvalˇ evaluates this expression in
the global environment and returns the result.
Í (eval '(+ 1 2)) ==> 3
Í (eval '(define x 1)) ==> ˘unspecifiedÍ
Í x ==> 1ˇ
Í(compile-file˘ filename option ...Í) ˇprocedure
˘Filenameˇ should be a string naming an existing file containing Scheme source code. Any of the
compilation options described below can be specified after the filename. ÍCompile-fileˇ
compiles the source file into an object file which can be loaded with the Íloadˇ procedure or
linked into a standalone application by the linker. By convention, source files have a ".scm"
extension. Object files have a ".O" extension.
The following options are accepted by the compiler:
Íverboseˇ -- Generates a trace of the compiler's actions.
Íreportˇ -- Produces a global variable usage report. Each global variable used in the program
is listed with 4 flags that indicate if the global variable is defined, referenced, mutated and
called.
Íexpansionˇ -- Shows the source code after macro expansion.
Ípvmˇ -- Produces a listing of the PVM code for the program on "<file>.pvm".
Íasmˇ -- Produces the assembly language output file "<file>.asm".
Ídebugˇ -- Generates code that includes information to aid debugging.
Note: The compiler is only available in the full version of MacGambit.
ÛD.8. Tracingˇ
Í(trace˘ ˇ<name>˘ ...Í) ˇsyntax
Í(untrace˘ ˇ<name>˘ ...Í) ˇsyntax
ÍTraceˇ starts tracing calls to the specified procedures. ÍUntraceˇ stops the tracing. The form
Í(trace)ˇ returns the names of the currently traced procedures and Í(untrace)ˇ stops the
tracing on all those procedures.
ÛD.9. Miscellaneousˇ
Í(error˘ string obj ...Í) ˇprocedure
ÍErrorˇ signals an error and causes a new read-eval-print loop to be entered. The message
displayed is Ístringˇ followed by the remaining arguments. The continuation of the
read-eval-print loop is the same as the one passed to Íerrorˇ. Thus, returning from the
read-eval-print loop causes a return from the call to Íerrorˇ.
Í (define (real-sqrt x)
Í (if (< x 0)
Í (error "bad value to real-sqrt:" x)
Í (sqrt x)))ˇ
Í(exit) ˇprocedure
ÍExitˇ causes the program to terminate.
Í(runtime) ˇprocedure
ÍRuntimeˇ returns the number of seconds since the program was started.
Í(set-gc-report˘ booleanÍ) ˇprocedure
ÍSet-gc-reportˇ controls the generation of reports on garbage collections. If the argument
is true, a brief report of memory usage is generated on every garbage collection.
ÛD.10. Graphicsˇ
Í(clear-graphics) ˇprocedure
Í(position-pen˘ x yÍ) ˇprocedure
Í(draw-line-to˘ x yÍ) ˇprocedure
Í(draw-point˘ x yÍ) ˇprocedure
Í(clear-point˘ x yÍ) ˇprocedure
Í(graphics-text˘ string x yÍ) ˇprocedure
MacGambit has a "drawing" window which supports simple graphics. This window is initially
hidden but it pops up when any of the above procedures are called. The coordinates of the
drawing window go from -200 to +200 in both the x (horizontal) and y (vertical) axis. The
window is scaled by a factor of 1/2 (i.e. a distance of 10 units corresponds to 5 pixels on
the screen). The origin is in the center of the window. Lines are drawn using a "pen".
ÍPosition-penˇ sets the position of the pen and calls to Ídraw-line-toˇ move the pen to a
new coordinate leaving a line behind. The other procedures do not move the pen.
ÛD.11. Text windowsˇ
Í(open-text-window˘ stringÍ) ˇprocedure
This procedure opens an editable text window with the given title and returns a port to
access the window. The port is both an input and output port. Writing to the port displays
text in the window. Reading from the port returns the expression (or text) that has been
typed in this window and "sent" with Ícmd-returnˇ (or Íenterˇ for text). Closing the port
closes the window.
ÛD.12. Toolbox interfaceˇ
Some of the most common Macintosh Toolbox routines are available as Scheme procedures.
BEWARE: these procedures do not check the validity of their arguments so it is easy to crash
the system by passing an illegal value.
In general the procedures take the same parameters as the corresponding definition in "Inside
Macintosh". The notable exception is for Quickdraw procedures. Instead of operating on the
"current grafport", the quickdraw procedures take an extra argument that specifies the port
to use. This is always the first parameter.
Here is a list of the procedures available:
Í; Windows
Í
Í(mac#newwindow bounds title visible procid behind goaway)
Í(mac#getnewwindow windowid behind)
Í(mac#disposewindow w)
Í(mac#selectwindow w)
Í(mac#hidewindow w)
Í(mac#showwindow w)
Í(mac#frontwindow)
Í(mac#findwindow pt w-cell) ; w-cell is a pair, the car is the result
Í(mac#trackgoaway w pt)
Í(mac#dragwindow w pt r)
Í(mac#invalrect port r)
Í(mac#beginupdate w)
Í(mac#endupdate w)
Í
Í; Quickdraw
Í
Í(mac#point v h)
Í(mac#point-v r)
Í(mac#point-h r)
Í(mac#point-v-set! r x)
Í(mac#point-h-set! r x)
Í
Í(mac#rect top left bottom right)
Í(mac#rect-top r)
Í(mac#rect-left r)
Í(mac#rect-bottom r)
Í(mac#rect-right r)
Í(mac#rect-top-set! r x)
Í(mac#rect-left-set! r x)
Í(mac#rect-bottom-set! r x)
Í(mac#rect-right-set! r x)
Í
Í(mac#openport port)
Í(mac#initport port)
Í(mac#closeport port)
Í(mac#setport port)
Í(mac#getport)
Í(mac#setorigin port h v)
Í(mac#backpat port pat)
Í(mac#hidecursor)
Í(mac#showcursor)
Í(mac#pensize port width height)
Í(mac#penmode port mode)
Í(mac#penpat port pat)
Í(mac#pennormal port)
Í(mac#moveto port h v)
Í(mac#move port dh dv)
Í(mac#lineto port h v)
Í(mac#line port dh dv)
Í(mac#textfont port font)
Í(mac#textface port face)
Í(mac#textmode port mode)
Í(mac#textsize port size)
Í(mac#spaceextra port extra)
Í(mac#drawchar port ch)
Í(mac#drawstring port s)
Í(mac#drawtext port textbuf firstbyte bytecount) ; textbuf is a string
Í(mac#charwidth port ch)
Í(mac#stringwidth port s)
Í(mac#textwidth port textbuf firstbyte bytecount) ; textbuf is a string
Í(mac#localtoglobal port pt)
Í(mac#globaltolocal port pt)
Í(mac#framerect port r)
Í(mac#paintrect port r)
Í(mac#eraserect port r)
Í(mac#invertrect port r)
Í(mac#fillrect port r pat)
Í(mac#frameroundrect port r ovwd ovht)
Í(mac#paintroundrect port r ovwd ovht)
Í(mac#eraseroundrect port r ovwd ovht)
Í(mac#invertroundrect port r ovwd ovht)
Í(mac#fillroundrect port r ovwd ovht pat)
Í(mac#frameoval port r)
Í(mac#paintoval port r)
Í(mac#eraseoval port r)
Í(mac#invertoval port r)
Í(mac#filloval port r pat)
Í(mac#framearc port r startangle arcangle)
Í(mac#paintarc port r startangle arcangle)
Í(mac#erasearc port r startangle arcangle)
Í(mac#invertarc port r startangle arcangle)
Í(mac#fillarc port r startangle arcangle pat)
Í
Í; Menus
Í
Í(mac#newmenu menuid str)
Í(mac#getmenu resourceid)
Í(mac#disposemenu themenu)
Í(mac#appendmenu themenu str)
Í(mac#addresmenu themenu thetype)
Í(mac#insertresmenu themenu thetype afteritem)
Í(mac#insertmenu themenu beforeid)
Í(mac#drawmenubar)
Í(mac#deletemenu menuid)
Í(mac#clearmenubar)
Í(mac#getnewmbar menubarid)
Í(mac#getmenubar)
Í(mac#setmenubar menulist)
Í(mac#menuselect p)
Í(mac#menukey ch)
Í(mac#hilitemenu menuid)
Í(mac#disableitem themenu item)
Í(mac#enableitem themenu item)
Í(mac#getmhandle menuid)
Í
Í; Events
Í
Í(mac#event-what event)
Í(mac#event-message event)
Í(mac#event-when event)
Í(mac#event-where event)
Í(mac#event-modifiers event)
Í
Í(mac#modifiers-button? modifiers)
Í(mac#modifiers-command? modifiers)
Í(mac#modifiers-shift? modifiers)
Í(mac#modifiers-alphalock? modifiers)
Í(mac#modifiers-option? modifiers)
Í
Í; Standard file get/put
Í
Í(mac#sfgetfile) ; returns a filename or #f
Í(mac#sfputfile) ; returns a filename or #f
Í
Í; Other procedures
Í
Í(mac#getmouse pt)
Í(mac#button)
Í(mac#tickcount)
Í(mac#delay duration)
Í(mac#sysbeep duration)
Í(mac#seteventmask themask)
͡
Û1. Overview of Schemeˇ
Û1.1. Semanticsˇ
This section gives an overview of Scheme's semantics. A detailed informal semantics is the
subject of chapters 3 through 6. For reference purposes, section 7.2 provides a formal
semantics of Scheme.
Following Algol, Scheme is a statically scoped programming language. Each use of a variable
is associated with a lexically apparent binding of that variable.
Scheme has latent as opposed to manifest types. Types are associated with values (also
called objects) rather than with variables. (Some authors refer to languages with latent
types as weakly typed or dynamically typed languages.) Other languages with latent types
are APL, Snobol, and other dialects of Lisp. Languages with manifest types (sometimes
referred to as strongly typed or statically typed languages) include Algol 60, Pascal, and C.
All objects created in the course of a Scheme computation, including procedures and
continuations, have unlimited extent. No Scheme object is ever destroyed. The reason that
implementations of Scheme do not (usually!) run out of storage is that they are permitted to
reclaim the storage occupied by an object if they can prove that the object cannot possibly
matter to any future computation. Other languages in which most objects have unlimited
extent include APL and other Lisp dialects.
Implementations of Scheme are required to be properly tail-recursive. This allows the
execution of an iterative computation in constant space, even if the iterative computation is
described by a syntactically recursive procedure. Thus with a tail-recursive
implementation, iteration can be expressed using the ordinary procedure-call mechanics, so
that special iteration constructs are useful only as syntactic sugar.
Scheme procedures are objects in their own right. Procedures can be created dynamically,
stored in data structures, returned as results of procedures, and so on. Other languages with
these properties include Common Lisp and ML.
One distinguishing feature of Scheme is that continuations, which in most other languages
only operate behind the scenes, also have ``first-class'' status. Continuations are useful for
implementing a wide variety of advanced control constructs, including non-local exits,
backtracking, and coroutines. See section 6.9.
Arguments to Scheme procedures are always passed by value, which means that the actual
argument expressions are evaluated before the procedure gains control, whether the
procedure needs the result of the evaluation or not. ML, C, and APL are three other
languages that always pass arguments by value. This is distinct from the lazy-evaluation
semantics of Haskell, or the call-by-name semantics of Algol 60, where an argument
expression is not evaluated unless its value is needed by the procedure.
Scheme's model of arithmetic is designed to remain as independent as possible of the
particular ways in which numbers are represented within a computer. In Scheme, every
integer is a rational number, every rational is a real, and every real is a complex number.
Thus the distinction between integer and real arithmetic, so important to many programming
languages, does not appear in Scheme. In its place is a distinction between exact arithmetic,
which corresponds to the mathematical ideal, and inexact arithmetic on approximations. As
in Common Lisp, exact arithmetic is not limited to integers.
Û1.2. Syntaxˇ
Scheme, like most dialects of Lisp, employs a fully parenthesized prefix notation for
programs and (other) data; the grammar of Scheme generates a sublanguage of the language
used for data. An important consequence of this simple, uniform representation is the
susceptibility of Scheme programs and data to uniform treatment by other Scheme
programs.
The Íreadˇ procedure performs syntactic as well as lexical decomposition of the data it reads.
The Íreadˇ procedure parses its input as data (section 7.1.2), not as program.
The formal syntax of Scheme is described in section 7.1.
Û1.3. Notation and terminologyˇ
¸1.3.1. Essential and non-essential featuresˇ
It is required that every implementation of Scheme support features that are marked as
being ˘essentialˇ. Features not explicitly marked as essential are not essential.
Implementations are free to omit non-essential features of Scheme or to add extensions,
provided the extensions are not in conflict with the language reported here. In particular,
implementations must support portable code by providing a syntactic mode that preempts no
lexical conventions of this report and reserves no identifiers other than those listed as
syntactic keywords in section 2.1.
¸1.3.2. Error situations and unspecified behaviorˇ
When speaking of an error situation, this report uses the phrase ``an error is signalled'' to
indicate that implementations must detect and report the error. If such wording does not
appear in the discussion of an error, then implementations are not required to detect or
report the error, though they are encouraged to do so. An error situation that
implementations are not required to detect is usually referred to simply as ``an error.''
For example, it is an error for a procedure to be passed an argument that the procedure is
not explicitly specified to handle, even though such domain errors are seldom mentioned in
this report. Implementations may extend a procedure's domain of definition to include such
arguments.
This report uses the phrase ``may report a violation of an implementation restriction'' to
indicate circumstances under which an implementation is permitted to report that it is unable
to continue execution of a correct program because of some restriction imposed by the
implementation. Implementation restrictions are of course discouraged, but implementations
are encouraged to report violations of implementation restrictions.
For example, an implementation may report a violation of an implementation restriction if it
does not have enough storage to run a program.
If the value of an expression is said to be ``unspecified,'' then the expression must evaluate
to some object without signalling an error, but the value depends on the implementation; this
report explicitly does not say what value should be returned.
¸1.3.3. Entry formatˇ
Chapters 4 and 6 are organized into entries. Each entry describes one language feature or a
group of related features, where a feature is either a syntactic construct or a built-in
procedure. An entry begins with one or more header lines of the form
˘templateÍ ˇessential ˘categoryˇ
if the feature is an essential feature, or simply
˘templateÍ ˇ ˘categoryˇ
if the feature is not an essential feature.
If ˘categoryˇ is ``syntax'', the entry describes an expression type, and the header line gives
the syntax of the expression type. Components of expressions are designated by syntactic
variables, which are written using angle brackets, for example, <expression>, <variable>.
Syntactic variables should be understood to denote segments of program text; for example,
<expression> stands for any string of characters which is a syntactically valid expression.
The notation
<thing˛1ˇ> ...
indicates zero or more occurrences of a <thing>, and
<thing˛1ˇ> <thing˛2ˇ> ...
indicates one or more occurrences of a <thing>.
If ˘categoryˇ is ``procedure'', then the entry describes a procedure, and the header line gives a
template for a call to the procedure. Argument names in the template are ˘italicizedˇ. Thus the
header line
Í(vector-ref ˘vectorÍ ˘kÍ) ˇessential procedure
indicates that the essential built-in procedure Ívector-refˇ takes two arguments, a vector
˘vectorˇ and an exact non-negative integer ˘kˇ (see below). The header lines
Í(make-vector ˘kÍ) ˇessential procedure
Í(make-vector ˘kÍ ˘fillÍ) ˇprocedure
indicate that in all implementations, the Ímake-vectorˇ procedure must be defined to take one
argument, and some implementations will extend it to take two arguments.
It is an error for an operation to be presented with an argument that it is not specified to
handle. For succinctness, we follow the convention that if an argument name is also the name
of a type listed in section 3.4, then that argument must be of the named type. For example,
the header line for Ívector-refˇ given above dictates that the first argument to
Ívector-refˇ must be a vector. The following naming conventions also imply type
restrictions:
˘objÍ ˇany object
˘listˇ, ˘list¯1ˇ, ... ˘list¯jˇ, ...Í ˇlist (see section 6.3)
˘zˇ, ˘z¯1ˇ, ... ˘z¯jˇ, ...Í ˇcomplex number
˘xˇ, ˘x¯1ˇ, ... ˘x¯jˇ, ...Í ˇreal number
˘yˇ, ˘y¯1ˇ, ... ˘y¯jˇ, ...Í ˇreal number
˘qˇ, ˘q¯1ˇ, ... ˘q¯jˇ, ...Í ˇrational number
˘nˇ, ˘n¯1ˇ, ... ˘n¯jˇ, ...Í ˇinteger
˘kˇ, ˘k¯1ˇ, ... ˘k¯jˇ, ...Í ˇexact non-negative integer
¸1.3.4. Evaluation examplesˇ
The symbol ``Í==>ˇ'' used in program examples should be read ``evaluates to.'' For example,
Í (* 5 8) ==> 40ˇ
means that the expression Í(* 5 8)ˇ evaluates to the object Í40ˇ. Or, more precisely: the
expression given by the sequence of characters ``Í(* 5 8)ˇ'' evaluates, in the initial
environment, to an object that may be represented externally by the sequence of characters
``Í40ˇ''. See section 3.3 for a discussion of external representations of objects.
¸1.3.5. Naming conventionsˇ
By convention, the names of procedures that always return a boolean value usually end in
``Í?ˇ''. Such procedures are called predicates.
By convention, the names of procedures that store values into previously allocated locations
(see section 3.5) usually end in ``Í!ˇ''. Such procedures are called mutation procedures. By
convention, the value returned by a mutation procedure is unspecified.
By convention, ``Í->ˇ'' appears within the names of procedures that take an object of one type
and return an analogous object of another type. For example, Ílist->vectorˇ takes a list and
returns a vector whose elements are the same as those of the list.
Û2. Lexical conventionsˇ
This section gives an informal account of some of the lexical conventions used in writing
Scheme programs. For a formal syntax of Scheme, see section 7.1.
Upper and lower case forms of a letter are never distinguished except within character and
string constants. For example, ÍFooˇ is the same identifier as ÍFOOˇ, and Í#x1ABˇ is the same
number as Í#X1abˇ.
Û2.1. Identifiersˇ
Most identifiers allowed by other programming languages are also acceptable to Scheme. The
precise rules for forming identifiers vary among implementations of Scheme, but in all
implementations a sequence of letters, digits, and ``extended alphabetic characters'' that
begins with a character that cannot begin a number is an identifier. In addition, Í+ˇ, Í-ˇ, and Í...ˇ
are identifiers. Here are some examples of identifiers:
Í lambda q
Í list->vector soup
Í + V17a
Í <=? a34kTMNs
Í the-word-recursion-has-many-meaningsˇ
Extended alphabetic characters may be used within identifiers as if they were letters. The
following are extended alphabetic characters:
Í + - . * / < = > ! ? : $ % _ & ~ ^ˇ
See section 7.1.1 for a formal syntax of identifiers.
Identifiers have several uses within Scheme programs:
• Certain identifiers are reserved for use as syntactic keywords (see below).
• Any identifier that is not a syntactic keyword may be used as a variable (see section 3.1).
• When an identifier appears as a literal or within a literal (see section 4.1.2), it is being
used to denote a ˘symbolˇ (see section 6.4).
The following identifiers are syntactic keywords, and should not be used as variables:
Í => do or
Í and else quasiquote
Í begin if quote
Í case lambda set!
Í cond let unquote
Í define let* unquote-splicing
Í delay letrecˇ
Some implementations allow all identifiers, including syntactic keywords, to be used as
variables. This is a compatible extension to the language, but ambiguities in the language
result when the restriction is relaxed, and the ways in which these ambiguities are resolved
vary between implementations.
Û2.2. Whitespace and commentsˇ
˘Whitespaceˇ characters are spaces and newlines. (Implementations typically provide
additional whitespace characters such as tab or page break.) Whitespace is used for
improved readability and as necessary to separate tokens from each other, a token being an
indivisible lexical unit such as an identifier or number, but is otherwise insignificant.
Whitespace may occur between any two tokens, but not within a token. Whitespace may also
occur inside a string, where it is significant.
A semicolon (Í;ˇ) indicates the start of a comment. The comment continues to the end of the
line on which the semicolon appears. Comments are invisible to Scheme, but the end of the
line is visible as whitespace. This prevents a comment from appearing in the middle of an
identifier or number.
Í ;;; The FACT procedure computes the factorial
Í ;;; of a non-negative integer.
Í (define fact
Í (lambda (n)
Í (if (= n 0)
Í 1 ;Base case: return 1
Í (* n (fact (- n 1))))))ˇ
Û2.3. Other notationsˇ
For a description of the notations used for numbers, see section 6.5.
Í. + -ˇ These are used in numbers, and may also occur anywhere in an identifier except as
the first character. A delimited plus or minus sign by itself is also an identifier. A delimited
period (not occurring within a number or identifier) is used in the notation for pairs (section
6.3), and to indicate a rest-parameter in a formal parameter list (section 4.1.4). A delimited
sequence of three successive periods is also an identifier.
Í( )ˇ Parentheses are used for grouping and to notate lists (section 6.3).
Í'ˇ The single quote character is used to indicate literal data (section 4.1.2).
Í`ˇ The backquote character is used to indicate almost-constant data (section 4.2.6).
Í, ,@ˇ The character comma and the sequence comma at-sign are used in conjunction with
backquote (section 4.2.6).
Í"ˇ The double quote character is used to delimit strings (section 6.7).
Í\ˇ Backslash is used in the syntax for character constants (section 6.6) and as an escape
character within string constants (section 6.7).
Í[ ] { }ˇ Left and right square brackets and curly braces are reserved for possible future
extensions to the language.
Í#ˇ Sharp sign is used for a variety of purposes depending on the character that immediately
follows it:
Í#tˇ Í#fˇ These are the boolean constants (section 6.1).
Í#\ˇ This introduces a character constant (section 6.6).
Í#(ˇ This introduces a vector constant (section 6.8). Vector constants are terminated by Í)ˇ .
Í#e #i #b #o #d #xˇ These are used in the notation for numbers (section 6.5.4).
Û3. Basic conceptsˇ
Û3.1. Variables and regionsˇ
Any identifier that is not a syntactic keyword (see section 2.1) may be used as a variable. A
variable may name a location where a value can be stored. A variable that does so is said to
be ˘boundˇ to the location. The set of all visible bindings in effect at some point in a program is
known as the ˘environmentˇ in effect at that point. The value stored in the location to which a
variable is bound is called the variable's value. By abuse of terminology, the variable is
sometimes said to name the value or to be bound to the value. This is not quite accurate, but
confusion rarely results from this practice.
Certain expression types are used to create new locations and to bind variables to those
locations. The most fundamental of these ˘binding constructsˇ is the lambda expression,
because all other binding constructs can be explained in terms of lambda expressions. The
other binding constructs are Íletˇ, Ílet*ˇ, Íletrecˇ, and Ídoˇ expressions (see sections 4.1.4,
4.2.2, and 4.2.4).
Like Algol and Pascal, and unlike most other dialects of Lisp except for Common Lisp, Scheme
is a statically scoped language with block structure. To each place where a variable is bound
in a program there corresponds a ˘regionˇ of the program text within which the binding is
effective. The region is determined by the particular binding construct that establishes the
binding; if the binding is established by a lambda expression, for example, then its region is
the entire lambda expression. Every reference to or assignment of a variable refers to the
binding of the variable that established the innermost of the regions containing the use. If
there is no binding of the variable whose region contains the use, then the use refers to the
binding for the variable in the top level environment, if any (section 6); if there is no binding
for the identifier, it is said to be ˘unboundˇ.
Û3.2. True and falseˇ
Any Scheme value can be used as a boolean value for the purpose of a conditional test. As
explained in section 6.1, all values count as true in such a test except for Í#fˇ. This report
uses the word ``true'' to refer to any Scheme value that counts as true, and the word
``false'' to refer to Í#fˇ.
˘Note:ˇ In some implementations the empty list also counts as false instead of true.
Û3.3. External representationsˇ
An important concept in Scheme (and Lisp) is that of the ˘external representationˇ of an object
as a sequence of characters. For example, an external representation of the integer 28 is the
sequence of characters ``Í28ˇ'', and an external representation of a list consisting of the
integers 8 and 13 is the sequence of characters ``Í(8 13)ˇ''.
The external representation of an object is not necessarily unique. The integer 28 also has
representations ``Í#e28.000ˇ'' and ``Í#x1cˇ'', and the list in the previous paragraph also has
the representations ``Í( 08 13 )ˇ'' and ``Í(8 . (13 . ()))ˇ'' (see section 6.3).
Many objects have standard external representations, but some, such as procedures, do not
have standard representations (although particular implementations may define
representations for them).
An external representation may be written in a program to obtain the corresponding object
(see Íquoteˇ, section 4.1.2).
External representations can also be used for input and output. The procedure Íreadˇ (section
6.10.2) parses external representations, and the procedure Íwriteˇ (section 6.10.3)
generates them. Together, they provide an elegant and powerful input/output facility.
Note that the sequence of characters ``Í(+ 2 6)ˇ'' is ˘notˇ an external representation of the
integer 8, even though it ˘isˇ an expression evaluating to the integer 8; rather, it is an
external representation of a three-element list, the elements of which are the symbol Í+ˇ and
the integers 2 and 6. Scheme's syntax has the property that any sequence of characters that
is an expression is also the external representation of some object. This can lead to
confusion, since it may not be obvious out of context whether a given sequence of characters
is intended to denote data or program, but it is also a source of power, since it facilitates
writing programs such as interpreters and compilers that treat programs as data (or vice
versa).
The syntax of external representations of various kinds of objects accompanies the
description of the primitives for manipulating the objects in the appropriate sections of
chapter 6.
Û3.4. Disjointness of typesˇ
No object satisfies more than one of the following predicates:
Í boolean? pair?
Í symbol? number?
Í char? string?
Í vector? procedure?ˇ
These predicates define the types ˘booleanˇ, ˘pairˇ, ˘symbolˇ, ˘numberˇ, ˘charˇ (or ˘characterˇ),
˘stringˇ, ˘vectorˇ, and ˘procedureˇ.
Û3.5. Storage modelˇ
Variables and objects such as pairs, vectors, and strings implicitly denote locations or
sequences of locations. A string, for example, denotes as many locations as there are
characters in the string. (These locations need not correspond to a full machine word.) A new
value may be stored into one of these locations using the Ístring-set!ˇ procedure, but the
string continues to denote the same locations as before.
An object fetched from a location, by a variable reference or by a procedure such as Ícarˇ,
Ívector-refˇ, or Ístring-refˇ, is equivalent in the sense of Íeqv?ˇ (section 6.2) to the object
last stored in the location before the fetch.
Every location is marked to show whether it is in use. No variable or object ever refers to a
location that is not in use. Whenever this report speaks of storage being allocated for a
variable or object, what is meant is that an appropriate number of locations are chosen from
the set of locations that are not in use, and the chosen locations are marked to indicate that
they are now in use before the variable or object is made to denote them.
In many systems it is desirable for constants (i.e. the values of literal expressions) to
reside in read-only-memory. To express this, it is convenient to imagine that every object
that denotes locations is associated with a flag telling whether that object is mutable or
immutable. The constants and the strings returned by Ísymbol->stringˇ are then the
immutable objects, while all objects created by the other procedures listed in this report are
mutable. It is an error to attempt to store a new value into a location that is denoted by an
immutable object.
Û4. Expressionsˇ
A Scheme expression is a construct that returns a value, such as a variable reference,
literal, procedure call, or conditional.
Expression types are categorized as ˘primitiveˇ or ˘derivedˇ. Primitive expression types
include variables and procedure calls. Derived expression types are not semantically
primitive, but can instead be explained in terms of the primitive constructs as in section 7.3.
They are redundant in the strict sense of the word, but they capture common patterns of
usage, and are therefore provided as convenient abbreviations.
Û4.1. Primitive expression typesˇ
¸4.1.1. Variable referencesˇ
<variable>Í ˇessential syntax
An expression consisting of a variable (section 3.1) is a variable reference. The value of the
variable reference is the value stored in the location to which the variable is bound. It is an
error to reference an unbound variable.
Í (define x 28)
Í x ==> 28ˇ
¸4.1.2. Literal expressionsˇ
Í(quote˘ ˇ<datum>Í) ˇessential syntax
Í'ˇ<datum>Í ˇessential syntax
<constant>Í ˇessential syntax
Í(quote ˇ<datum>Í)ˇ evaluates to <datum>. <Datum> may be any external representation of a
Scheme object (see section 3.3). This notation is used to include literal constants in Scheme
code.
Í (quote a) ==> a
Í (quote #(a b c)) ==> #(a b c)
Í (quote (+ 1 2)) ==> (+ 1 2)ˇ
Í(quote ˇ<datum>Í)ˇ may be abbreviated as Í'ˇ<datum>. The two notations are equivalent in all
respects.
Í 'a ==> a
Í '#(a b c) ==> #(a b c)
Í '() ==> ()
Í '(+ 1 2) ==> (+ 1 2)
Í '(quote a) ==> (quote a)
Í ''a ==> (quote a)ˇ
Numerical constants, string constants, character constants, and boolean constants evaluate
``to themselves''; they need not be quoted.
Í '"abc" ==> "abc"
Í "abc" ==> "abc"
Í '145932 ==> 145932
Í 145932 ==> 145932
Í '#t ==> #t
Í #t ==> #tˇ
As noted in section 3.5, it is an error to alter a constant (i.e. the value of a literal
expression) using a mutation procedure like Íset-car!ˇ or Ístring-set!ˇ.
¸4.1.3. Procedure callsˇ
Í(ˇ<operator>Í ˇ<operand˛1ˇ>Í ...) ˇessential syntax
A procedure call is written by simply enclosing in parentheses expressions for the procedure
to be called and the arguments to be passed to it. The operator and operand expressions are
evaluated (in an unspecified order) and the resulting procedure is passed the resulting
arguments.
Í (+ 3 4) ==> 7
Í ((if #f + *) 3 4) ==> 12ˇ
A number of procedures are available as the values of variables in the initial environment;
for example, the addition and multiplication procedures in the above examples are the values
of the variables Í+ˇ and Í*ˇ. New procedures are created by evaluating lambda expressions (see
section 4.1.4).
Procedure calls are also called ˘combinationsˇ.
˘Note:ˇ In contrast to other dialects of Lisp, the order of evaluation is unspecified, and the
operator expression and the operand expressions are always evaluated with the same
evaluation rules.
˘Note:ˇ Although the order of evaluation is otherwise unspecified, the effect of any concurrent
evaluation of the operator and operand expressions is constrained to be consistent with some
sequential order of evaluation. The order of evaluation may be chosen differently for each
procedure call.
˘Note:ˇ In many dialects of Lisp, the empty combination, Í()ˇ, is a legitimate expression. In
Scheme, combinations must have at least one subexpression, so Í()ˇ is not a syntactically
valid expression.
¸4.1.4. Lambda expressionsˇ
Í(lambda˘ ˇ<formals>˘ ˇ<body>Í) ˇessential syntax
˘Syntax:ˇ <Formals> should be a formal arguments list as described below, and <body> should
be a sequence of one or more expressions.
˘Semantics:ˇ A lambda expression evaluates to a procedure. The environment in effect when
the lambda expression was evaluated is remembered as part of the procedure. When the
procedure is later called with some actual arguments, the environment in which the lambda
expression was evaluated will be extended by binding the variables in the formal argument
list to fresh locations, the corresponding actual argument values will be stored in those
locations, and the expressions in the body of the lambda expression will be evaluated
sequentially in the extended environment. The result of the last expression in the body will
be returned as the result of the procedure call.
Í (lambda (x) (+ x x)) ==> ˘a procedureÍ
Í ((lambda (x) (+ x x)) 4) ==> 8
Í
Í (define reverse-subtract
Í (lambda (x y) (- y x)))
Í (reverse-subtract 7 10) ==> 3
Í
Í (define add4
Í (let ((x 4))
Í (lambda (y) (+ x y))))
Í (add4 6) ==> 10ˇ
<Formals> should have one of the following forms:
• Í(ˇ<variable˛1ˇ>Í ...)ˇ: The procedure takes a fixed number of arguments; when the
procedure is called, the arguments will be stored in the bindings of the corresponding
variables.
• <variable>: The procedure takes any number of arguments; when the procedure is called,
the sequence of actual arguments is converted into a newly allocated list, and the list is
stored in the binding of the <variable>.
• Í(ˇ<variable˛1ˇ>Í ... ˇ<variable˛n-1ˇ>Í . ˇ<variable˛nˇ>Í)ˇ: If a space-delimited period precedes
the last variable, then the value stored in the binding of the last variable will be a newly
allocated list of the actual arguments left over after all the other actual arguments have
been matched up against the other formal arguments.
It is an error for a <variable> to appear more than once in <formals>.
Í ((lambda x x) 3 4 5 6) ==> (3 4 5 6)
Í ((lambda (x y . z) z)
Í 3 4 5 6) ==> (5 6)ˇ
Each procedure created as the result of evaluating a lambda expression is tagged with a
storage location, in order to make Íeqv?ˇ and Íeq?ˇ work on procedures (see section 6.2).
¸4.1.5. Conditionalsˇ
Í(if˘ ˇ<test>˘ ˇ<consequent>˘ ˇ<alternate>Í) ˇessential syntax
Í(if˘ ˇ<test>˘ ˇ<consequent>Í) ˇsyntax
˘Syntax:ˇ <Test>, <consequent>, and <alternate> may be arbitrary expressions.
˘Semantics:ˇ An Íifˇ expression is evaluated as follows: first, <test> is evaluated. If it yields a
true value (see section 6.1), then <consequent> is evaluated and its value is returned.
Otherwise <alternate> is evaluated and its value is returned. If <test> yields a false value
and no <alternate> is specified, then the result of the expression is unspecified.
Í (if (> 3 2) 'yes 'no) ==> yes
Í (if (> 2 3) 'yes 'no) ==> no
Í (if (> 3 2)
Í (- 3 2)
Í (+ 3 2)) ==> 1ˇ
¸4.1.6. Assignmentsˇ
Í(set!˘ ˇ<variable>˘ ˇ<expression>Í) ˇessential syntax
<Expression> is evaluated, and the resulting value is stored in the location to which
<variable> is bound. <Variable> must be bound either in some region enclosing the Íset!ˇ
expression or at top level. The result of the Íset!ˇ expression is unspecified.
Í (define x 2)
Í (+ x 1) ==> 3
Í (set! x 4) ==> ˘unspecifiedÍ
Í (+ x 1) ==> 5ˇ
Û4.2. Derived expression typesˇ
For reference purposes, section 7.3 gives rewrite rules that will convert constructs
described in this section into the primitive constructs described in the previous section.
¸4.2.1. Conditionalsˇ
Í(cond˘ ˇ<clause˛1ˇ>˘ ˇ<clause˛2ˇ>˘ ...Í) ˇessential syntax
˘Syntax:ˇ Each <clause> should be of the form Í(ˇ<test>Í ˇ<expression>Í ...)ˇ where <test> is
any expression. The last <clause> may be an ``else clause,'' which has the form Í(else
͡<expression˛1ˇ>Í ˇ<expression˛2ˇ>Í ...).ˇ
˘Semantics:ˇ A Ícondˇ expression is evaluated by evaluating the <test> expressions of
successive <clause>s in order until one of them evaluates to a true value (see section 6.1).
When a <test> evaluates to a true value, then the remaining <expression>s in its <clause> are
evaluated in order, and the result of the last <expression> in the <clause> is returned as the
result of the entire Ícondˇ expression. If the selected <clause> contains only the <test> and no
<expression>s, then the value of the <test> is returned as the result. If all <test>s evaluate
to false values, and there is no else clause, then the result of the conditional expression is
unspecified; if there is an else clause, then its <expression>s are evaluated, and the value of
the last one is returned.
Í (cond ((> 3 2) 'greater)
Í ((< 3 2) 'less)) ==> greater
Í (cond ((> 3 3) 'greater)
Í ((< 3 3) 'less)
Í (else 'equal)) ==> equalˇ
Some implementations support an alternative <clause> syntax, Í(ˇ<test>Í => ˇ<recipient>Í)ˇ,
where <recipient> is an expression. If <test> evaluates to a true value, then <recipient> is
evaluated. Its value must be a procedure of one argument; this procedure is then invoked on
the value of the <test>.
Í (cond ((assv 'b '((a 1) (b 2))) => cadr)
Í (else #f)) ==> 2ˇ
Í(case˘ ˇ<key>˘ ˇ<clause˛1ˇ>˘ ˇ<clause˛2ˇ>˘ ...Í) ˇessential syntax
˘Syntax:ˇ <Key> may be any expression. Each <clause> should have the form Í((ˇ<datum˛1ˇ>Í
Í...) ˇ<expression˛1ˇ>Í ˇ<expression˛2ˇ>Í ...),ˇ where each <datum> is an external
representation of some object. All the <datum>s must be distinct. The last <clause> may be
an ``else clause,'' which has the form Í(else ˇ<expression˛1ˇ>Í ˇ<expression˛2ˇ>Í ...).ˇ
˘Semantics:ˇ A Ícaseˇ expression is evaluated as follows. <Key> is evaluated and its result is
compared against each <datum>. If the result of evaluating <key> is equivalent (in the sense
of Íeqv?ˇ; see section 6.2) to a <datum>, then the expressions in the corresponding <clause>
are evaluated from left to right and the result of the last expression in the <clause> is
returned as the result of the Ícaseˇ expression. If the result of evaluating <key> is different
from every <datum>, then if there is an else clause its expressions are evaluated and the
result of the last is the result of the Ícaseˇ expression; otherwise the result of the Ícaseˇ
expression is unspecified.
Í (case (* 2 3)
Í ((2 3 5 7) 'prime)
Í ((1 4 6 8 9) 'composite)) ==> composite
Í (case (car '(c d))
Í ((a) 'a)
Í ((b) 'b)) ==> ˘unspecifiedÍ
Í (case (car '(c d))
Í ((a e i o u) 'vowel)
Í ((w y) 'semivowel)
Í (else 'consonant)) ==> consonantˇ
Í(and˘ ˇ<test˛1ˇ>˘ ...Í) ˇessential syntax
The <test> expressions are evaluated from left to right, and the value of the first expression
that evaluates to a false value (see section 6.1) is returned. Any remaining expressions are
not evaluated. If all the expressions evaluate to true values, the value of the last expression
is returned. If there are no expressions then Í#tˇ is returned.
Í (and (= 2 2) (> 2 1)) ==> #t
Í (and (= 2 2) (< 2 1)) ==> #f
Í (and 1 2 'c '(f g)) ==> (f g)
Í (and) ==> #tˇ
Í(or˘ ˇ<test˛1ˇ>˘ ...Í) ˇessential syntax
The <test> expressions are evaluated from left to right, and the value of the first expression
that evaluates to a true value (see section 6.1) is returned. Any remaining expressions are
not evaluated. If all expressions evaluate to false values, the value of the last expression is
returned. If there are no expressions then Í#fˇ is returned.
Í (or (= 2 2) (> 2 1)) ==> #t
Í (or (= 2 2) (< 2 1)) ==> #t
Í (or #f #f #f) ==> #f
Í (or (memq 'b '(a b c))
Í (/ 3 0)) ==> (b c)ˇ
¸4.2.2. Binding constructsˇ
The three binding constructs Íletˇ, Ílet*ˇ, and Íletrecˇ give Scheme a block structure, like
Algol 60. The syntax of the three constructs is identical, but they differ in the regions they
establish for their variable bindings. In a Íletˇ expression, the initial values are computed
before any of the variables become bound; in a Ílet*ˇ expression, the bindings and evaluations
are performed sequentially; while in a Íletrecˇ expression, all the bindings are in effect
while their initial values are being computed, thus allowing mutually recursive definitions.
Í(let˘ ˇ<bindings>˘ ˇ<body>Í) ˇessential syntax
˘Syntax:ˇ <Bindings> should have the form Í((ˇ<variable˛1ˇ>Í ˇ<init˛1ˇ>Í) ...),ˇ where each <init>
is an expression, and <body> should be a sequence of one or more expressions. It is an error
for a <variable> to appear more than once in the list of variables being bound.
˘Semantics:ˇ The <init>s are evaluated in the current environment (in some unspecified order),
the <variable>s are bound to fresh locations holding the results, the <body> is evaluated in
the extended environment, and the value of the last expression of <body> is returned. Each
binding of a <variable> has <body> as its region.
Í (let ((x 2) (y 3))
Í (* x y)) ==> 6
Í
Í (let ((x 2) (y 3))
Í (let ((x 7)
Í (z (+ x y)))
Í (* z x))) ==> 35ˇ
See also named Íletˇ, section 4.2.4.
Í(let*˘ ˇ<bindings>˘ ˇ<body>Í) ˇsyntax
˘Syntax:ˇ <Bindings> should have the form Í((ˇ<variable˛1ˇ>Í ˇ<init˛1ˇ>Í) ...),ˇ and <body> should
be a sequence of one or more expressions.
˘Semantics:ˇ ÍLet*ˇ is similar to Íletˇ, but the bindings are performed sequentially from left to
right, and the region of a binding indicated by Í(ˇ<variable>Í ˇ<init>Í)ˇ is that part of the Ílet*ˇ
expression to the right of the binding. Thus the second binding is done in an environment in
which the first binding is visible, and so on.
Í (let ((x 2) (y 3))
Í (let* ((x 7)
Í (z (+ x y)))
Í (* z x))) ==> 70ˇ
Í(letrec˘ ˇ<bindings>˘ ˇ<body>Í) ˇessential syntax
˘Syntax:ˇ <Bindings> should have the form Í((ˇ<variable˛1ˇ>Í ˇ<init˛1ˇ>Í) ...),ˇ and <body> should
be a sequence of one or more expressions. It is an error for a <variable> to appear more than
once in the list of variables being bound.
˘Semantics:ˇ The <variable>s are bound to fresh locations holding undefined values, the <init>s
are evaluated in the resulting environment (in some unspecified order), each <variable> is
assigned to the result of the corresponding <init>, the <body> is evaluated in the resulting
environment, and the value of the last expression in <body> is returned. Each binding of a
<variable> has the entire Íletrecˇ expression as its region, making it possible to define
mutually recursive procedures.
Í (letrec ((even?
Í (lambda (n)
Í (if (zero? n)
Í #t
Í (odd? (- n 1)))))
Í (odd?
Í (lambda (n)
Í (if (zero? n)
Í #f
Í (even? (- n 1))))))
Í (even? 88))
Í ==> #tˇ
One restriction on Íletrecˇ is very important: it must be possible to evaluate each <init>
without assigning or referring to the value of any <variable>. If this restriction is violated,
then it is an error. The restriction is necessary because Scheme passes arguments by value
rather than by name. In the most common uses of Íletrecˇ, all the <init>s are lambda
expressions and the restriction is satisfied automatically.
¸4.2.3. Sequencingˇ
Í(begin˘ ˇ<expression˛1ˇ>˘ ˇ<expression˛2ˇ>˘ ...Í) ˇessential syntax
The <expression>s are evaluated sequentially from left to right, and the value of the last
<expression> is returned. This expression type is used to sequence side effects such as input
and output.
Í (define x 0)
Í
Í (begin (set! x 5)
Í (+ x 1)) ==> 6
Í
Í (begin (display "4 plus 1 equals ")
Í (display (+ 4 1))) ==> ˘unspecifiedÍ
Í ˘and printsÍ 4 plus 1 equals 5ˇ
˘Note:ˇ [SICP] uses the keyword Ísequenceˇ instead of Íbeginˇ.
¸4.2.4. Iterationˇ
Í(do ((ˇ<variable˛1ˇ>Í ˇ<init˛1ˇ>Í ˇ<step˛1ˇ>Í) ˇsyntax Í
Í ...)
Í (ˇ<test>Í ˇ<expression>Í ...)
Í ˇ<command>Í ...)ˇ
ÍDoˇ is an iteration construct. It specifies a set of variables to be bound, how they are to be
initialized at the start, and how they are to be updated on each iteration. When a termination
condition is met, the loop exits with a specified result value.
ÍDoˇ expressions are evaluated as follows: The <init> expressions are evaluated (in some
unspecified order), the <variable>s are bound to fresh locations, the results of the <init>
expressions are stored in the bindings of the <variable>s, and then the iteration phase begins.
Each iteration begins by evaluating <test>; if the result is false (see section 6.1), then the
<command> expressions are evaluated in order for effect, the <step> expressions are
evaluated in some unspecified order, the <variable>s are bound to fresh locations, the
results of the <step>s are stored in the bindings of the <variable>s, and the next iteration
begins.
If <test> evaluates to a true value, then the <expression>s are evaluated from left to right
and the value of the last <expression> is returned as the value of the Ídoˇ expression. If no
<expression>s are present, then the value of the Ídoˇ expression is unspecified.
The region of the binding of a <variable> consists of the entire Ídoˇ expression except for the
<init>s. It is an error for a <variable> to appear more than once in the list of Ídoˇ variables.
A <step> may be omitted, in which case the effect is the same as if Í(ˇ<variable>Í ˇ<init>Í
͡<variable>Í)ˇ had been written instead of Í(ˇ<variable>Í ˇ<init>Í)ˇ.
Í (do ((vec (make-vector 5))
Í (i 0 (+ i 1)))
Í ((= i 5) vec)
Í (vector-set! vec i i)) ==> #(0 1 2 3 4)
Í
Í (let ((x '(1 3 5 7 9)))
Í (do ((x x (cdr x))
Í (sum 0 (+ sum (car x))))
Í ((null? x) sum))) ==> 25ˇ
Í(let˘ ˇ<variable>˘ ˇ<bindings>˘ ˇ<body>Í) ˇsyntax
Some implementations of Scheme permit a variant on the syntax of Íletˇ called ``named Íletˇ''
which provides a more general looping construct than Ídoˇ, and may also be used to express
recursions.
Named Íletˇ has the same syntax and semantics as ordinary Íletˇ except that <variable> is
bound within <body> to a procedure whose formal arguments are the bound variables and
whose body is <body>. Thus the execution of <body> may be repeated by invoking the
procedure named by <variable>.
Í (let loop ((numbers '(3 -2 1 6 -5))
Í (nonneg '())
Í (neg '()))
Í (cond ((null? numbers) (list nonneg neg))
Í ((>= (car numbers) 0)
Í (loop (cdr numbers)
Í (cons (car numbers) nonneg)
Í neg))
Í ((< (car numbers) 0)
Í (loop (cdr numbers)
Í nonneg
Í (cons (car numbers) neg)))))
Í ==> ((6 1 3) (-5 -2))ˇ
¸4.2.5. Delayed evaluationˇ
Í(delay˘ ˇ<expression>Í) ˇsyntax
The Ídelayˇ construct is used together with the procedure Íforceˇ to implement ˘lazy
˘evaluationˇ or ˘call by needˇ. Í(delay ˇ<expression>Í)ˇ returns an object called a ˘promiseˇ which
at some point in the future may be asked (by the Íforceˇ procedure) to evaluate <expression>
and deliver the resulting value.
See the description of Íforceˇ (section 6.9) for a more complete description of Ídelayˇ.
¸4.2.6. Quasiquotationˇ
Í(quasiquote˘ ˇ<template>Í) ˇessential syntax
Í`ˇ<template>Í ˇessential syntax
``Backquote'' or ``quasiquote'' expressions are useful for constructing a list or vector
structure when most but not all of the desired structure is known in advance. If no commas
appear within the <template>, the result of evaluating Í`ˇ<template> is equivalent to the result
of evaluating Í'ˇ<template>. If a comma appears within the <template>, however, the
expression following the comma is evaluated (``unquoted'') and its result is inserted into the
structure instead of the comma and the expression. If a comma appears followed immediately
by an at-sign (Í@ˇ), then the following expression must evaluate to a list; the opening and
closing parentheses of the list are then ``stripped away'' and the elements of the list are
inserted in place of the comma at-sign expression sequence.
Í `(list ,(+ 1 2) 4) ==> (list 3 4)
Í (let ((name 'a)) `(list ,name ',name))
Í ==> (list a (quote a))
Í `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)
Í ==> (a 3 4 5 6 b)
Í `((foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))
Í ==> ((foo 7) . cons)
Í `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)
Í ==> #(10 5 2 4 3 8)ˇ
Quasiquote forms may be nested. Substitutions are made only for unquoted components
appearing at the same nesting level as the outermost backquote. The nesting level increases
by one inside each successive quasiquotation, and decreases by one inside each unquotation.
Í `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)
Í ==> (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
Í (let ((name1 'x)
Í (name2 'y))
Í `(a `(b ,,name1 ,',name2 d) e))
Í ==> (a `(b ,x ,'y d) e)ˇ
The notations Í`ˇ<template> and Í(quasiquote ˇ<template>Í)ˇ are identical in all respects.
Í,ˇ<expression> is identical to Í(unquote ˇ<expression>Í)ˇ, and Í,@ˇ<expression> is identical to
Í(unquote-splicing ˇ<expression>Í)ˇ. The external syntax generated by Íwriteˇ for
two-element lists whose car is one of these symbols may vary between implementations.
Í (quasiquote (list (unquote (+ 1 2)) 4))
Í ==> (list 3 4)
Í '(quasiquote (list (unquote (+ 1 2)) 4))
Í ==> `(list ,(+ 1 2) 4)
Í ˘i.e.,Í (quasiquote (list (unquote (+ 1 2)) 4))ˇ
Unpredictable behavior can result if any of the symbols Íquasiquoteˇ, Íunquoteˇ, or
Íunquote-splicingˇ appear in positions within a <template> otherwise than as described
above.
Û5. Program structureˇ
Û5.1. Programsˇ
A Scheme program consists of a sequence of expressions and definitions. Expressions are
described in chapter 4; definitions are the subject of the rest of the present chapter.
Programs are typically stored in files or entered interactively to a running Scheme system,
although other paradigms are possible; questions of user interface lie outside the scope of
this report. (Indeed, Scheme would still be useful as a notation for expressing computational
methods even in the absence of a mechanical implementation.)
Definitions occurring at the top level of a program can be interpreted declaratively. They
cause bindings to be created in the top level environment. Expressions occurring at the top
level of a program are interpreted imperatively; they are executed in order when the
program is invoked or loaded, and typically perform some kind of initialization.
Û5.2. Definitionsˇ
Definitions are valid in some, but not all, contexts where expressions are allowed. They are
valid only at the top level of a <program> and, in some implementations, at the beginning of a
<body>.
A definition should have one of the following forms:
• Í(define ˇ<variable>Í ˇ<expression>Í)ˇ
This syntax is essential.
• Í(define (ˇ<variable>Í ˇ<formals>Í) ˇ<body>Í)ˇ
This syntax is not essential. <Formals> should be either a sequence of zero or more
variables, or a sequence of one or more variables followed by a space-delimited period and
another variable (as in a lambda expression). This form is equivalent to
Í (define ˇ<variable>Í
Í (lambda (ˇ<formals>Í) ˇ<body>Í)).ˇ
• Í(define (ˇ<variable>Í . ˇ<formal>Í) ˇ<body>Í)ˇ
This syntax is not essential. <Formal> should be a single variable. This form is equivalent to
Í (define ˇ<variable>Í
Í (lambda ˇ<formal>Í ˇ<body>Í)).ˇ
• Í(begin ˇ<definition˛1ˇ>Í ...)ˇ
This syntax is essential. This form is equivalent to the set of definitions that form the body
of the Íbeginˇ.
¸5.2.1. Top level definitionsˇ
At the top level of a program, a definition
Í (define ˇ<variable>Í ˇ<expression>Í)ˇ
has essentially the same effect as the assignment expression
Í (set! ˇ<variable>Í ˇ<expression>Í)ˇ
if <variable> is bound. If <variable> is not bound, however, then the definition will bind
<variable> to a new location before performing the assignment, whereas it would be an error
to perform a Íset!ˇ on an unbound variable.
Í (define add3
Í (lambda (x) (+ x 3)))
Í (add3 3) ==> 6
Í (define first car)
Í (first '(1 2)) ==> 1ˇ
All Scheme implementations must support top level definitions.
Some implementations of Scheme use an initial environment in which all possible variables
are bound to locations, most of which contain undefined values. Top level definitions in such
an implementation are truly equivalent to assignments.
¸5.2.2. Internal definitionsˇ
Some implementations of Scheme permit definitions to occur at the beginning of a <body>
(that is, the body of a Ílambdaˇ, Íletˇ, Ílet*ˇ, Íletrecˇ, or Ídefineˇ expression). Such
definitions are known as ˘internal definitionsˇ as opposed to the top level definitions described
above. The variable defined by an internal definition is local to the <body>. That is,
<variable> is bound rather than assigned, and the region of the binding is the entire <body>.
For example,
Í (let ((x 5))
Í (define foo (lambda (y) (bar x y)))
Í (define bar (lambda (a b) (+ (* a b) a)))
Í (foo (+ x 3))) ==> 45ˇ
A <body> containing internal definitions can always be converted into a completely equivalent
Íletrecˇ expression. For example, the Íletˇ expression in the above example is equivalent to
Í (let ((x 5))
Í (letrec ((foo (lambda (y) (bar x y)))
Í (bar (lambda (a b) (+ (* a b) a))))
Í (foo (+ x 3))))ˇ
Just as for the equivalent Íletrecˇ expression, it must be possible to evaluate each
<expression> of every internal definition in a <body> without assigning or referring to the
value of any <variable> being defined.
Û6. Standard proceduresˇ
This chapter describes Scheme's built-in procedures. The initial (or ``top level'') Scheme
environment starts out with a number of variables bound to locations containing useful
values, most of which are primitive procedures that manipulate data. For example, the
variable Íabsˇ is bound to (a location initially containing) a procedure of one argument that
computes the absolute value of a number, and the variable Í+ˇ is bound to a procedure that
computes sums.
Û6.1. Booleansˇ
The standard boolean objects for true and false are written as Í#tˇ and Í#fˇ. What really
matters, though, are the objects that the Scheme conditional expressions (Íifˇ, Ícondˇ, Íandˇ,
Íorˇ, Ídoˇ) treat as true or false. The phrase ``a true value'' (or sometimes just ``true'') means
any object treated as true by the conditional expressions, and the phrase ``a false value'' (or
``false'') means any object treated as false by the conditional expressions.
Of all the standard Scheme values, only Í#fˇ counts as false in conditional expressions. Except
for Í#fˇ, all standard Scheme values, including Í#tˇ, pairs, the empty list, symbols, numbers,
strings, vectors, and procedures, count as true.
˘Note:ˇ In some implementations the empty list counts as false, contrary to the above.
Nonetheless a few examples in this report assume that the empty list counts as true, as in
[IEEE-Scheme].
˘Note:ˇ Programmers accustomed to other dialects of Lisp should be aware that Scheme
distinguishes both Í#fˇ and the empty list from the symbol Ínilˇ.
Boolean constants evaluate to themselves, so they don't need to be quoted in programs.
Í #t ==> #t
Í #f ==> #f
Í '#f ==> #fˇ
Í(not˘ objÍ) ˇessential procedure
ÍNotˇ returns Í#tˇ if ˘objˇ is false, and returns Í#fˇ otherwise.
Í (not #t) ==> #f
Í (not 3) ==> #f
Í (not (list 3)) ==> #f
Í (not #f) ==> #t
Í (not '()) ==> #f
Í (not (list)) ==> #f
Í (not 'nil) ==> #fˇ
Í(boolean?˘ objÍ) ˇessential procedure
ÍBoolean?ˇ returns Í#tˇ if ˘objˇ is either Í#tˇ or Í#fˇ and returns Í#fˇ otherwise.
Í (boolean? #f) ==> #t
Í (boolean? 0) ==> #f
Í (boolean? '()) ==> #fˇ
Û6.2. Equivalence predicatesˇ
A ˘predicateˇ is a procedure that always returns a boolean value (Í#tˇ or Í#fˇ). An ˘equivalence
˘predicateˇ is the computational analogue of a mathematical equivalence relation (it is
symmetric, reflexive, and transitive). Of the equivalence predicates described in this
section, Íeq?ˇ is the finest or most discriminating, and Íequal?ˇ is the coarsest. ÍEqv?ˇ is
slightly less discriminating than Íeq?ˇ.
Í(eqv?˘ obj¯1˘ obj¯2Í) ˇessential procedure
The Íeqv?ˇ procedure defines a useful equivalence relation on objects. Briefly, it returns Í#tˇ if
˘obj¯1ˇ and ˘obj¯2ˇ should normally be regarded as the same object. This relation is left slightly
open to interpretation, but the following partial specification of Íeqv?ˇ holds for all
implementations of Scheme.
The Íeqv?ˇ procedure returns Í#tˇ if:
• ˘obj¯1ˇ and ˘obj¯2ˇ are both Í#tˇ or both Í#fˇ.
• ˘obj¯1ˇ and ˘obj¯2ˇ are both symbols and
Í (string=? (symbol->string ˘obj¯1Í)
Í (symbol->string ˘obj¯2Í))
Í ==> #tˇ
˘Note:ˇ This assumes that neither ˘obj¯1ˇ nor ˘obj¯2ˇ is an ``uninterned symbol'' as alluded to in
section 6.4. This report does not presume to specify the behavior of Íeqv?ˇ on
implementation-dependent extensions.
• ˘obj¯1ˇ and ˘obj¯2ˇ are both numbers, are numerically equal (see Í=ˇ, section 6.5), and are either
both exact or both inexact.
• ˘obj¯1ˇ and ˘obj¯2ˇ are both characters and are the same character according to the Íchar=?ˇ
procedure (section 6.6).
• both ˘obj¯1ˇ and ˘obj¯2ˇ are the empty list.
• ˘obj¯1ˇ and ˘obj¯2ˇ are pairs, vectors, or strings that denote the same locations in the store
(section 3.5).
• ˘obj¯1ˇ and ˘obj¯2ˇ are procedures whose location tags are equal (section 4.1.4).
The Íeqv?ˇ procedure returns Í#fˇ if:
• ˘obj¯1ˇ and ˘obj¯2ˇ are of different types (section 3.4).
• one of ˘obj¯1ˇ and ˘obj¯2ˇ is Í#tˇ but the other is Í#fˇ.
• ˘obj¯1ˇ and ˘obj¯2ˇ are symbols but
Í (string=? (symbol->string ˘obj¯1Í)
Í (symbol->string ˘obj¯2Í))
Í ==> #fˇ
• one of ˘obj¯1ˇ and ˘obj¯2ˇ is an exact number but the other is an inexact number.
• ˘obj¯1ˇ and ˘obj¯2ˇ are numbers for which the Í=ˇ procedure returns Í#fˇ.
• ˘obj¯1ˇ and ˘obj¯2ˇ are characters for which the Íchar=?ˇ procedure returns Í#fˇ.
• one of ˘obj¯1ˇ and ˘obj¯2ˇ is the empty list but the other is not.
• ˘obj¯1ˇ and ˘obj¯2ˇ are pairs, vectors, or strings that denote distinct locations.
• ˘obj¯1ˇ and ˘obj¯2ˇ are procedures that would behave differently (return a different value or
have different side effects) for some arguments.
Í (eqv? 'a 'a) ==> #t
Í (eqv? 'a 'b) ==> #f
Í (eqv? 2 2) ==> #t
Í (eqv? '() '()) ==> #t
Í (eqv? 100000000 100000000) ==> #t
Í (eqv? (cons 1 2) (cons 1 2))==> #f
Í (eqv? (lambda () 1)
Í (lambda () 2)) ==> #f
Í (eqv? #f 'nil) ==> #f
Í (let ((p (lambda (x) x)))
Í (eqv? p p)) ==> #tˇ
The following examples illustrate cases in which the above rules do not fully specify the
behavior of Íeqv?ˇ. All that can be said about such cases is that the value returned by Íeqv?ˇ
must be a boolean.
Í (eqv? "" "") ==> ˘unspecifiedÍ
Í (eqv? '#() '#()) ==> ˘unspecifiedÍ
Í (eqv? (lambda (x) x)
Í (lambda (x) x)) ==> ˘unspecifiedÍ
Í (eqv? (lambda (x) x)
Í (lambda (y) y)) ==> ˘unspecifiedˇ
The next set of examples shows the use of Íeqv?ˇ with procedures that have local state.
ÍGen-counterˇ must return a distinct procedure every time, since each procedure has its
own internal counter. ÍGen-loserˇ, however, returns equivalent procedures each time, since
the local state does not affect the value or side effects of the procedures.
Í (define gen-counter
Í (lambda ()
Í (let ((n 0))
Í (lambda () (set! n (+ n 1)) n))))
Í (let ((g (gen-counter)))
Í (eqv? g g)) ==> #t
Í (eqv? (gen-counter) (gen-counter))
Í ==> #f
Í (define gen-loser
Í (lambda ()
Í (let ((n 0))
Í (lambda () (set! n (+ n 1)) 27))))
Í (let ((g (gen-loser)))
Í (eqv? g g)) ==> #t
Í (eqv? (gen-loser) (gen-loser))
Í ==> ˘unspecifiedÍ
Í
Í (letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
Í (g (lambda () (if (eqv? f g) 'both 'g)))
Í (eqv? f g))
Í ==> ˘unspecifiedÍ
Í
Í (letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
Í (g (lambda () (if (eqv? f g) 'g 'both)))
Í (eqv? f g))
Í ==> #fˇ
Since it is an error to modify constant objects (those returned by literal expressions),
implementations are permitted, though not required, to share structure between constants
where appropriate. Thus the value of Íeqv?ˇ on constants is sometimes
implementation-dependent.
Í (eqv? '(a) '(a)) ==> ˘unspecifiedÍ
Í (eqv? "a" "a") ==> ˘unspecifiedÍ
Í (eqv? '(b) (cdr '(a b))) ==> ˘unspecifiedÍ
Í (let ((x '(a)))
Í (eqv? x x)) ==> #tˇ
˘Rationale:ˇ The above definition of Íeqv?ˇ allows implementations latitude in their treatment of
procedures and literals: implementations are free either to detect or to fail to detect that
two procedures or two literals are equivalent to each other, and can decide whether or not
to merge representations of equivalent objects by using the same pointer or bit pattern to
represent both.
Í(eq?˘ obj¯1˘ obj¯2Í) ˇessential procedure
ÍEq?ˇ is similar to Íeqv?ˇ except that in some cases it is capable of discerning distinctions finer
than those detectable by Íeqv?ˇ.
ÍEq?ˇ and Íeqv?ˇ are guaranteed to have the same behavior on symbols, booleans, the empty
list, pairs, and non-empty strings and vectors. ÍEq?ˇ's behavior on numbers and characters is
implementation-dependent, but it will always return either true or false, and will return
true only when Íeqv?ˇ would also return true. ÍEq?ˇ may also behave differently from Íeqv?ˇ on
empty vectors and empty strings.
Í (eq? 'a 'a) ==> #t
Í (eq? '(a) '(a)) ==> ˘unspecifiedÍ
Í (eq? (list 'a) (list 'a)) ==> #f
Í (eq? "a" "a") ==> ˘unspecifiedÍ
Í (eq? "" "") ==> ˘unspecifiedÍ
Í (eq? '() '()) ==> #t
Í (eq? 2 2) ==> ˘unspecifiedÍ
Í (eq? #\A #\A) ==> ˘unspecifiedÍ
Í (eq? car car) ==> #t
Í (let ((n (+ 2 3)))
Í (eq? n n)) ==> ˘unspecifiedÍ
Í (let ((x '(a)))
Í (eq? x x)) ==> #t
Í (let ((x '#()))
Í (eq? x x)) ==> #t
Í (let ((p (lambda (x) x)))
Í (eq? p p)) ==> #tˇ
˘Rationale:ˇ It will usually be possible to implement Íeq?ˇ much more efficiently than Íeqv?ˇ, for
example, as a simple pointer comparison instead of as some more complicated operation. One
reason is that it may not be possible to compute Íeqv?ˇ of two numbers in constant time,
whereas Íeq?ˇ implemented as pointer comparison will always finish in constant time. ÍEq?ˇ
may be used like Íeqv?ˇ in applications using procedures to implement objects with state since
it obeys the same constraints as Íeqv?ˇ.
Í(equal?˘ obj¯1˘ obj¯2Í) ˇessential procedure
ÍEqual?ˇ recursively compares the contents of pairs, vectors, and strings, applying Íeqv?ˇ on
other objects such as numbers and symbols. A rule of thumb is that objects are generally
Íequal?ˇ if they print the same. ÍEqual?ˇ may fail to terminate if its arguments are circular
data structures.
Í (equal? 'a 'a) ==> #t
Í (equal? '(a) '(a)) ==> #t
Í (equal? '(a (b) c)
Í '(a (b) c)) ==> #t
Í (equal? "abc" "abc") ==> #t
Í (equal? 2 2) ==> #t
Í (equal? (make-vector 5 'a)
Í (make-vector 5 'a)) ==> #t
Í (equal? (lambda (x) x)
Í (lambda (y) y)) ==> ˘unspecifiedˇ
Û6.3. Pairs and listsˇ
A ˘pairˇ (sometimes called a ˘dotted pairˇ) is a record structure with two fields called the car
and cdr fields (for historical reasons). Pairs are created by the procedure Íconsˇ. The car and
cdr fields are accessed by the procedures Ícarˇ and Ícdrˇ. The car and cdr fields are assigned
by the procedures Íset-car!ˇ and Íset-cdr!ˇ.
Pairs are used primarily to represent lists. A list can be defined recursively as either the
empty list or a pair whose cdr is a list. More precisely, the set of lists is defined as the
smallest set ˘Xˇ such that
• The empty list is in ˘Xˇ.
• If ˘listˇ is in ˘Xˇ, then any pair whose cdr field contains ˘listˇ is also in ˘Xˇ.
The objects in the car fields of successive pairs of a list are the elements of the list. For
example, a two-element list is a pair whose car is the first element and whose cdr is a pair
whose car is the second element and whose cdr is the empty list. The length of a list is the
number of elements, which is the same as the number of pairs.
The empty list is a special object of its own type (it is not a pair); it has no elements and its
length is zero.
˘Note:ˇ The above definitions imply that all lists have finite length and are terminated by the
empty list.
The most general notation (external representation) for Scheme pairs is the ``dotted''
notation Í(˘c¯1Í . ˘c¯2Í)ˇ where ˘c¯1ˇ is the value of the car field and ˘c¯2ˇ is the value of the cdr
field. For example Í(4 . 5)ˇ is a pair whose car is 4 and whose cdr is 5. Note that Í(4 . 5)ˇ
is the external representation of a pair, not an expression that evaluates to a pair.
A more streamlined notation can be used for lists: the elements of the list are simply
enclosed in parentheses and separated by spaces. The empty list is written Í()ˇ. For example,
Í (a b c d e)ˇ
and
Í (a . (b . (c . (d . (e . ())))))ˇ
are equivalent notations for a list of symbols.
A chain of pairs not ending in the empty list is called an ˘improper listˇ. Note that an improper
list is not a list. The list and dotted notations can be combined to represent improper lists:
Í (a b c . d)ˇ
is equivalent to
Í (a . (b . (c . d)))ˇ
Whether a given pair is a list depends upon what is stored in the cdr field. When the
Íset-cdr!ˇ procedure is used, an object can be a list one moment and not the next:
Í (define x (list 'a 'b 'c))
Í (define y x)
Í y ==> (a b c)
Í (list? y) ==> #t
Í (set-cdr! x 4) ==> ˘unspecifiedÍ
Í x ==> (a . 4)
Í (eqv? x y) ==> #t
Í y ==> (a . 4)
Í (list? y) ==> #f
Í (set-cdr! x x) ==> ˘unspecifiedÍ
Í (list? x) ==> #fˇ
Within literal expressions and representations of objects read by the Íreadˇ procedure, the
forms Í'ˇ<datum>, Í`ˇ<datum>, Í,ˇ<datum>, and Í,@ˇ<datum> denote two-element lists whose first
elements are the symbols Íquoteˇ, Íquasiquoteˇ, Íunquoteˇ, and Íunquote-splicingˇ,
respectively. The second element in each case is <datum>. This convention is supported so
that arbitrary Scheme programs may be represented as lists. That is, according to Scheme's
grammar, every <expression> is also a <datum> (see section 7.1.2). Among other things,
this permits the use of the Íreadˇ procedure to parse Scheme programs. See section 3.3.
Í(pair?˘ objÍ) ˇessential procedure
ÍPair?ˇ returns Í#tˇ if ˘objˇ is a pair, and otherwise returns Í#fˇ.
Í (pair? '(a . b)) ==> #t
Í (pair? '(a b c)) ==> #t
Í (pair? '()) ==> #f
Í (pair? '#(a b)) ==> #fˇ
Í(cons˘ obj¯1˘ obj¯2Í) ˇessential procedure
Returns a newly allocated pair whose car is ˘obj¯1ˇ and whose cdr is ˘obj¯2ˇ. The pair is
guaranteed to be different (in the sense of Íeqv?ˇ) from every existing object.
Í (cons 'a '()) ==> (a)
Í (cons '(a) '(b c d)) ==> ((a) b c d)
Í (cons "a" '(b c)) ==> ("a" b c)
Í (cons 'a 3) ==> (a . 3)
Í (cons '(a b) 'c) ==> ((a b) . c)ˇ
Í(car˘ pairÍ) ˇessential procedure
Returns the contents of the car field of ˘pairˇ. Note that it is an error to take the car of the
empty list.
Í (car '(a b c)) ==> a
Í (car '((a) b c d)) ==> (a)
Í (car '(1 . 2)) ==> 1
Í (car '()) ==> ˘errorˇ
Í(cdr˘ pairÍ) ˇessential procedure
Returns the contents of the cdr field of ˘pairˇ. Note that it is an error to take the cdr of the
empty list.
Í (cdr '((a) b c d)) ==> (b c d)
Í (cdr '(1 . 2)) ==> 2
Í (cdr '()) ==> ˘errorˇ
Í(set-car!˘ pair objÍ) ˇessential procedure
Stores ˘objˇ in the car field of ˘pairˇ. The value returned by Íset-car!ˇ is unspecified.
Í (define (f) (list 'not-a-constant-list))
Í (define (g) '(constant-list))
Í (set-car! (f) 3) ==> ˘unspecifiedÍ
Í (set-car! (g) 3) ==> ˘errorˇ
Í(set-cdr!˘ pair objÍ) ˇessential procedure
Stores ˘objˇ in the cdr field of ˘pairˇ. The value returned by Íset-cdr!ˇ is unspecified.
Í(caar˘ pairÍ) ˇessential procedure
Í(cadr˘ pairÍ) ˇessential procedure
.
.
.
Í(cdddar˘ pairÍ) ˇessential procedure
Í(cddddr˘ pairÍ) ˇessential procedure
These procedures are compositions of Ícarˇ and Ícdrˇ, where for example Ícaddrˇ could be
defined by
Í (define caddr (lambda (x) (car (cdr (cdr x))))).ˇ
Arbitrary compositions, up to four deep, are provided. There are twenty-eight of these
procedures in all.
Í(null?˘ objÍ) ˇessential procedure
Returns Í#tˇ if ˘objˇ is the empty list, otherwise returns Í#fˇ.
Í(list?˘ objÍ) ˇessential procedure
Returns Í#tˇ if ˘objˇ is a list, otherwise returns Í#fˇ. By definition, all lists have finite length
and are terminated by the empty list.
Í (list? '(a b c)) ==> #t
Í (list? '()) ==> #t
Í (list? '(a . b)) ==> #f
Í (let ((x (list 'a)))
Í (set-cdr! x x)
Í (list? x)) ==> #fˇ
Í(list˘ obj ...Í) ˇessential procedure
Returns a newly allocated list of its arguments.
Í (list 'a (+ 3 4) 'c) ==> (a 7 c)
Í (list) ==> ()ˇ
Í(length˘ listÍ) ˇessential procedure
Returns the length of ˘listˇ.
Í (length '(a b c)) ==> 3
Í (length '(a (b) (c d e))) ==> 3
Í (length '()) ==> 0ˇ
Í(append˘ list ...Í) ˇessential procedure
Returns a list consisting of the elements of the first ˘listˇ followed by the elements of the
other ˘listˇs.
Í (append '(x) '(y)) ==> (x y)
Í (append '(a) '(b c d)) ==> (a b c d)
Í (append '(a (b)) '((c))) ==> (a (b) (c))ˇ
The resulting list is always newly allocated, except that it shares structure with the last
˘listˇ argument. The last argument may actually be any object; an improper list results if the
last argument is not a proper list.
Í (append '(a b) '(c . d)) ==> (a b c . d)
Í (append '() 'a) ==> aˇ
Í(reverse˘ listÍ) ˇessential procedure
Returns a newly allocated list consisting of the elements of ˘listˇ in reverse order.
Í (reverse '(a b c)) ==> (c b a)
Í (reverse '(a (b c) d (e (f))))
Í ==> ((e (f)) d (b c) a)ˇ
Í(list-tail˘ list kÍ) ˇprocedure
Returns the sublist of ˘listˇ obtained by omitting the first ˘kˇ elements. ÍList-tailˇ could be
defined by
Í (define list-tail
Í (lambda (x k)
Í (if (zero? k)
Í x
Í (list-tail (cdr x) (- k 1)))))ˇ
Í(list-ref˘ list kÍ) ˇessential procedure
Returns the ˘kˇth element of ˘listˇ. (This is the same as the car of Í(list-tail ˘listÍ ˘kÍ)ˇ.)
Í (list-ref '(a b c d) 2) ==> c
Í (list-ref '(a b c d)
Í (inexact->exact (round 1.8)))
Í ==> cˇ
Í(memq˘ obj listÍ) ˇessential procedure
Í(memv˘ obj listÍ) ˇessential procedure
Í(member˘ obj listÍ) ˇessential procedure
These procedures return the first sublist of ˘listˇ whose car is ˘objˇ, where the sublists of ˘listˇ
are the non-empty lists returned by Í(list-tail ˘listÍ ˘kÍ)ˇ for ˘kˇ less than the length of ˘listˇ.
If ˘objˇ does not occur in ˘listˇ, then Í#fˇ (not the empty list) is returned. ÍMemqˇ uses Íeq?ˇ to
compare ˘objˇ with the elements of ˘listˇ, while Ímemvˇ uses Íeqv?ˇ and Ímemberˇ uses Íequal?ˇ.
Í (memq 'a '(a b c)) ==> (a b c)
Í (memq 'b '(a b c)) ==> (b c)
Í (memq 'a '(b c d)) ==> #f
Í (memq (list 'a) '(b (a) c)) ==> #f
Í (member (list 'a)
Í '(b (a) c)) ==> ((a) c)
Í (memq 101 '(100 101 102)) ==> ˘unspecifiedÍ
Í (memv 101 '(100 101 102)) ==> (101 102)ˇ
Í(assq˘ obj alistÍ) ˇessential procedure
Í(assv˘ obj alistÍ) ˇessential procedure
Í(assoc˘ obj alistÍ) ˇessential procedure
˘Alistˇ (for ``association list'') must be a list of pairs. These procedures find the first pair in
˘alistˇ whose car field is ˘objˇ, and returns that pair. If no pair in ˘alistˇ has ˘objˇ as its car, then
Í#fˇ (not the empty list) is returned. ÍAssqˇ uses Íeq?ˇ to compare ˘objˇ with the car fields of the
pairs in ˘alistˇ, while Íassvˇ uses Íeqv?ˇ and Íassocˇ uses Íequal?ˇ.
Í (define e '((a 1) (b 2) (c 3)))
Í (assq 'a e) ==> (a 1)
Í (assq 'b e) ==> (b 2)
Í (assq 'd e) ==> #f
Í (assq (list 'a) '(((a)) ((b)) ((c))))
Í ==> #f
Í (assoc (list 'a) '(((a)) ((b)) ((c))))
Í ==> ((a))
Í (assq 5 '((2 3) (5 7) (11 13)))
Í ==> ˘unspecifiedÍ
Í (assv 5 '((2 3) (5 7) (11 13)))
Í ==> (5 7)ˇ
˘Rationale:ˇ Although they are ordinarily used as predicates, Ímemqˇ, Ímemvˇ, Ímemberˇ, Íassqˇ,
Íassvˇ, and Íassocˇ do not have question marks in their names because they return useful
values rather than just Í#tˇ or Í#fˇ.
Û6.4. Symbolsˇ
Symbols are objects whose usefulness rests on the fact that two symbols are identical (in
the sense of Íeqv?ˇ) if and only if their names are spelled the same way. This is exactly the
property needed to represent identifiers in programs, and so most implementations of
Scheme use them internally for that purpose. Symbols are useful for many other
applications; for instance, they may be used the way enumerated values are used in Pascal.
The rules for writing a symbol are exactly the same as the rules for writing an identifier;
see sections 2.1 and 7.1.1.
It is guaranteed that any symbol that has been returned as part of a literal expression, or
read using the Íreadˇ procedure, and subsequently written out using the Íwriteˇ procedure,
will read back in as the identical symbol (in the sense of Íeqv?ˇ). The Ístring->symbolˇ
procedure, however, can create symbols for which this write/read invariance may not hold
because their names contain special characters or letters in the non-standard case.
˘Note:ˇ Some implementations of Scheme have a feature known as ``slashification'' in order to
guarantee write/read invariance for all symbols, but historically the most important use of
this feature has been to compensate for the lack of a string data type.
Some implementations also have ``uninterned symbols'', which defeat write/read invariance
even in implementations with slashification, and also generate exceptions to the rule that
two symbols are the same if and only if their names are spelled the same.
Í(symbol?˘ objÍ) ˇessential procedure
Returns Í#tˇ if ˘objˇ is a symbol, otherwise returns Í#fˇ.
Í (symbol? 'foo) ==> #t
Í (symbol? (car '(a b))) ==> #t
Í (symbol? "bar") ==> #f
Í (symbol? 'nil) ==> #t
Í (symbol? '()) ==> #f
Í (symbol? #f) ==> #fˇ
Í(symbol->string˘ symbolÍ) ˇessential procedure
Returns the name of ˘symbolˇ as a string. If the symbol was part of an object returned as the
value of a literal expression (section 4.1.2) or by a call to the Íreadˇ procedure, and its name
contains alphabetic characters, then the string returned will contain characters in the
implementation's preferred standard case; some implementations will prefer upper case,
others lower case. If the symbol was returned by Ístring->symbolˇ, the case of characters
in the string returned will be the same as the case in the string that was passed to
Ístring->symbolˇ. It is an error to apply mutation procedures like Ístring-set!ˇ to strings
returned by this procedure.
The following examples assume that the implementation's standard case is lower case:
Í (symbol->string 'flying-fish)
Í ==> "flying-fish"
Í (symbol->string 'Martin) ==> "martin"
Í (symbol->string
Í (string->symbol "Malvina"))
Í ==> "Malvina"ˇ
Í(string->symbol˘ stringÍ) ˇessential procedure
Returns the symbol whose name is ˘stringˇ. This procedure can create symbols with names
containing special characters or letters in the non-standard case, but it is usually a bad idea
to create such symbols because in some implementations of Scheme they cannot be read as
themselves. See Ísymbol->stringˇ.
The following examples assume that the implementation's standard case is lower case:
Í (eq? 'mISSISSIppi 'mississippi)
Í ==> #t
Í (string->symbol "mISSISSIppi")
Í ==> ˇthe symbol with nameÍ "mISSISSIppi"
Í (eq? 'bitBlt (string->symbol "bitBlt"))
Í ==> #f
Í (eq? 'JollyWog
Í (string->symbol
Í (symbol->string 'JollyWog)))
Í ==> #t
Í (string=? "K. Harper, M.D."
Í (symbol->string
Í (string->symbol "K. Harper, M.D.")))
Í ==> #tˇ
Û6.5. Numbersˇ
Numerical computation has traditionally been neglected by the Lisp community. Until Common
Lisp there was no carefully thought out strategy for organizing numerical computation, and
with the exception of the MacLisp system [Pitman] little effort was made to execute
numerical code efficiently. This report recognizes the excellent work of the Common Lisp
committee and accepts many of their recommendations. In some ways this report simplifies
and generalizes their proposals in a manner consistent with the purposes of Scheme.
It is important to distinguish between the mathematical numbers, the Scheme numbers that
attempt to model them, the machine representations used to implement the Scheme numbers,
and notations used to write numbers. This report uses the types ˘numberˇ, ˘complexˇ, ˘realˇ,
˘rationalˇ, and ˘integerˇ to refer to both mathematical numbers and Scheme numbers. Machine
representations such as fixed point and floating point are referred to by names such as
˘fixnumˇ and ˘flonumˇ.
¸6.5.1. Numerical typesˇ
Mathematically, numbers may be arranged into a tower of subtypes in which each level is a
subset of the level above it:
number
complex
real
rational
integer
For example, 3 is an integer. Therefore 3 is also a rational, a real, and a complex. The same
is true of the Scheme numbers that model 3. For Scheme numbers, these types are defined
by the predicates Ínumber?ˇ, Ícomplex?ˇ, Íreal?ˇ, Írational?ˇ, and Íinteger?ˇ.
There is no simple relationship between a number's type and its representation inside a
computer. Although most implementations of Scheme will offer at least two different
representations of 3, these different representations denote the same integer.
Scheme's numerical operations treat numbers as abstract data, as independent of their
representation as possible. Although an implementation of Scheme may use fixnum, flonum,
and perhaps other representations for numbers, this should not be apparent to a casual
programmer writing simple programs.
It is necessary, however, to distinguish between numbers that are represented exactly and
those that may not be. For example, indexes into data structures must be known exactly, as
must some polynomial coefficients in a symbolic algebra system. On the other hand, the
results of measurements are inherently inexact, and irrational numbers may be
approximated by rational and therefore inexact approximations. In order to catch uses of
inexact numbers where exact numbers are required, Scheme explicitly distinguishes exact
from inexact numbers. This distinction is orthogonal to the dimension of type.
¸6.5.2. Exactnessˇ
Scheme numbers are either ˘exactˇ or ˘inexactˇ. A number is exact if it was written as an exact
constant or was derived from exact numbers using only exact operations. A number is
inexact if it was written as an inexact constant, if it was derived using inexact ingredients,
or if it was derived using inexact operations. Thus inexactness is a contagious property of a
number.
If two implementations produce exact results for a computation that did not involve inexact
intermediate results, the two ultimate results will be mathematically equivalent. This is
generally not true of computations involving inexact numbers since approximate methods
such as floating point arithmetic may be used, but it is the duty of each implementation to
make the result as close as practical to the mathematically ideal result.
Rational operations such as Í+ˇ should always produce exact results when given exact
arguments. If the operation is unable to produce an exact result, then it may either report
the violation of an implementation restriction or it may silently coerce its result to an
inexact value. See section 6.5.3.
With the exception of Íinexact->exactˇ, the operations described in this section must
generally return inexact results when given any inexact arguments. An operation may,
however, return an exact result if it can prove that the value of the result is unaffected by
the inexactness of its arguments. For example, multiplication of any number by an exact
zero may produce an exact zero result, even if the other argument is inexact.
¸6.5.3. Implementation restrictionsˇ
Implementations of Scheme are not required to implement the whole tower of subtypes given
in section 6.5.1, but they must implement a coherent subset consistent with both the
purposes of the implementation and the spirit of the Scheme language. For example, an
implementation in which all numbers are real may still be quite useful.
Implementations may also support only a limited range of numbers of any type, subject to
the requirements of this section. The supported range for exact numbers of any type may be
different from the supported range for inexact numbers of that type. For example, an
implementation that uses flonums to represent all its inexact real numbers may support a
practically unbounded range of exact integers and rationals while limiting the range of
inexact reals (and therefore the range of inexact integers and rationals) to the dynamic
range of the flonum format. Furthermore the gaps between the representable inexact
integers and rationals are likely to be very large in such an implementation as the limits of
this range are approached.
An implementation of Scheme must support exact integers throughout the range of numbers
that may be used for indexes of lists, vectors, and strings or that may result from
computing the length of a list, vector, or string. The Ílengthˇ, Ívector-lengthˇ, and
Ístring-lengthˇ procedures must return an exact integer, and it is an error to use anything
but an exact integer as an index. Furthermore any integer constant within the index range, if
expressed by an exact integer syntax, will indeed be read as an exact integer, regardless of
any implementation restrictions that may apply outside this range. Finally, the procedures
listed below will always return an exact integer result provided all their arguments are
exact integers and the mathematically expected result is representable as an exact integer
within the implementation:
Í + - *
Í quotient remainder modulo
Í max min abs
Í numerator denominator gcd
Í lcm floor ceiling
Í truncate round rationalize
Í exptˇ
Implementations are encouraged, but not required, to support exact integers and exact
rationals of practically unlimited size and precision, and to implement the above procedures
and the Í/ˇ procedure in such a way that they always return exact results when given exact
arguments. If one of these procedures is unable to deliver an exact result when given exact
arguments, then it may either report a violation of an implementation restriction or it may
silently coerce its result to an inexact number. Such a coercion may cause an error later.
An implementation may use floating point and other approximate representation strategies
for inexact numbers. This report recommends, but does not require, that the IEEE 32-bit and
64-bit floating point standards be followed by implementations that use flonum
representations, and that implementations using other representations should match or
exceed the precision achievable using these floating point standards [IEEE].
In particular, implementations that use flonum representations must follow these rules: A
flonum result must be represented with at least as much precision as is used to express any
of the inexact arguments to that operation. It is desirable (but not required) for potentially
inexact operations such as Ísqrtˇ, when applied to exact arguments, to produce exact
answers whenever possible (for example the square root of an exact 4 ought to be an exact
2). If, however, an exact number is operated upon so as to produce an inexact result (as by
Ísqrtˇ), and if the result is represented as a flonum, then the most precise flonum format
available must be used; but if the result is represented in some other way then the
representation must have at least as much precision as the most precise flonum format
available.
Although Scheme allows a variety of written notations for numbers, any particular
implementation may support only some of them. For example, an implementation in which all
numbers are real need not support the rectangular and polar notations for complex numbers.
If an implementation encounters an exact numerical constant that it cannot represent as an
exact number, then it may either report a violation of an implementation restriction or it
may silently represent the constant by an inexact number.
¸6.5.4. Syntax of numerical constantsˇ
The syntax of the written representations for numbers is described formally in section
7.1.1.
A number may be written in binary, octal, decimal, or hexadecimal by the use of a radix
prefix. The radix prefixes are Í#bˇ (binary), Í#oˇ (octal), Í#dˇ (decimal), and Í#xˇ (hexadecimal).
With no radix prefix, a number is assumed to be expressed in decimal.
A numerical constant may be specified to be either exact or inexact by a prefix. The
prefixes are Í#eˇ for exact, and Í#iˇ for inexact. An exactness prefix may appear before or
after any radix prefix that is used. If the written representation of a number has no
exactness prefix, the constant may be either inexact or exact. It is inexact if it contains a
decimal point, an exponent, or a ``Í#ˇ'' character in the place of a digit, otherwise it is exact.
In systems with inexact numbers of varying precisions it may be useful to specify the
precision of a constant. For this purpose, numerical constants may be written with an
exponent marker that indicates the desired precision of the inexact representation. The
letters Ísˇ, Ífˇ, Ídˇ, and Ílˇ specify the use of ˘shortˇ, ˘singleˇ, ˘doubleˇ, and ˘longˇ precision,
respectively. (When fewer than four internal inexact representations exist, the four size
specifications are mapped onto those available. For example, an implementation with two
internal representations may map short and single together and long and double together.) In
addition, the exponent marker Íeˇ specifies the default precision for the implementation. The
default precision has at least as much precision as ˘doubleˇ, but implementations may wish to
allow this default to be set by the user.
Í 3.14159265358979F0
Í ˇRound to single:Í 3.141593
Í 0.6L0
Í ˇExtend to long:Í .600000000000000ˇ
¸6.5.5. Numerical operationsˇ
The reader is referred to section 1.3.3 for a summary of the naming conventions used to
specify restrictions on the types of arguments to numerical routines. The examples used in
this section assume that any numerical constant written using an exact notation is indeed
represented as an exact number. Some examples also assume that certain numerical
constants written using an inexact notation can be represented without loss of accuracy; the
inexact constants were chosen so that this is likely to be true in implementations that use
flonums to represent inexact numbers.
Í(number?˘ objÍ) ˇessential procedure
Í(complex?˘ objÍ) ˇessential procedure
Í(real?˘ objÍ) ˇessential procedure
Í(rational?˘ objÍ) ˇessential procedure
Í(integer?˘ objÍ) ˇessential procedure
These numerical type predicates can be applied to any kind of argument, including
non-numbers. They return Í#tˇ if the object is of the named type, and otherwise they return
Í#fˇ. In general, if a type predicate is true of a number then all higher type predicates are also
true of that number. Consequently, if a type predicate is false of a number, then all lower
type predicates are also false of that number.
If ˘zˇ is an inexact complex number, then Í(real? ˘zÍ)ˇ is true if and only if Í(zero?
Í(imag-part ˘zÍ))ˇ is true. If ˘xˇ is an inexact real number, then Í(integer? ˘xÍ)ˇ is true if and
only if Í(= ˘xÍ (round ˘xÍ))ˇ.
Í (complex? 3+4i) ==> #t
Í (complex? 3) ==> #t
Í (real? 3) ==> #t
Í (real? -2.5+0.0i) ==> #t
Í (real? #e1e10) ==> #t
Í (rational? 6/10) ==> #t
Í (rational? 6/3) ==> #t
Í (integer? 3+0i) ==> #t
Í (integer? 3.0) ==> #t
Í (integer? 8/4) ==> #tˇ
˘Note:ˇ The behavior of these type predicates on inexact numbers is unreliable, since any
inaccuracy may affect the result.
˘Note:ˇ In many implementations the Írational?ˇ procedure will be the same as Íreal?ˇ, and
the Ícomplex?ˇ procedure will be the same as Ínumber?ˇ, but unusual implementations may be
able to represent some irrational numbers exactly or may extend the number system to
support some kind of non-complex numbers.
Í(exact?˘ zÍ) ˇessential procedure
Í(inexact?˘ zÍ) ˇessential procedure
These numerical predicates provide tests for the exactness of a quantity. For any Scheme
number, precisely one of these predicates is true.
Í(=˘ z¯1˘ z¯2˘ z¯3˘ ...Í) ˇessential procedure
Í(<˘ x¯1˘ x¯2˘ x¯3˘ ...Í) ˇessential procedure
Í(>˘ x¯1˘ x¯2˘ x¯3˘ ...Í) ˇessential procedure
Í(<=˘ x¯1˘ x¯2˘ x¯3˘ ...Í) ˇessential procedure
Í(>=˘ x¯1˘ x¯2˘ x¯3˘ ...Í) ˇessential procedure
These procedures return Í#tˇ if their arguments are (respectively): equal, monotonically
increasing, monotonically decreasing, monotonically nondecreasing, or monotonically
nonincreasing.
These predicates are required to be transitive.
˘Note:ˇ The traditional implementations of these predicates in Lisp-like languages are not
transitive.
˘Note:ˇ While it is not an error to compare inexact numbers using these predicates, the results
may be unreliable because a small inaccuracy may affect the result; this is especially true of
Í=ˇ and Ízero?ˇ. When in doubt, consult a numerical analyst.
Í(zero?˘ zÍ) ˇessential procedure
Í(positive?˘ xÍ) ˇessential procedure
Í(negative?˘ xÍ) ˇessential procedure
Í(odd?˘ nÍ) ˇessential procedure
Í(even?˘ nÍ) ˇessential procedure
These numerical predicates test a number for a particular property, returning Í#tˇ or Í#fˇ. See
note above.
Í(max˘ x¯1˘ x¯2˘ ...Í) ˇessential procedure
Í(min˘ x¯1˘ x¯2˘ ...Í) ˇessential procedure
These procedures return the maximum or minimum of their arguments.
Í (max 3 4) ==> 4 ; exact
Í (max 3.9 4) ==> 4.0 ; inexactˇ
˘Note:ˇ If any argument is inexact, then the result will also be inexact (unless the procedure
can prove that the inaccuracy is not large enough to affect the result, which is possible only
in unusual implementations). If Íminˇ or Ímaxˇ is used to compare numbers of mixed exactness,
and the numerical value of the result cannot be represented as an inexact number without
loss of accuracy, then the procedure may report a violation of an implementation restriction.
Í(+˘ z¯1˘ ...Í) ˇessential procedure
Í(*˘ z¯1˘ ...Í) ˇessential procedure
These procedures return the sum or product of their arguments.
Í (+ 3 4) ==> 7
Í (+ 3) ==> 3
Í (+) ==> 0
Í (* 4) ==> 4
Í (*) ==> 1ˇ
Í(-˘ z¯1˘ z¯2Í) ˇessential procedure
Í(-˘ zÍ) ˇessential procedure
Í(-˘ z¯1˘ z¯2˘ ...Í) ˇprocedure
Í(/˘ z¯1˘ z¯2Í) ˇessential procedure
Í(/˘ zÍ) ˇessential procedure
Í(/˘ z¯1˘ z¯2˘ ...Í) ˇprocedure
With two or more arguments, these procedures return the difference or quotient of their
arguments, associating to the left. With one argument, however, they return the additive or
multiplicative inverse of their argument.
Í (- 3 4) ==> -1
Í (- 3 4 5) ==> -6
Í (- 3) ==> -3
Í (/ 3 4 5) ==> 3/20
Í (/ 3) ==> 1/3ˇ
Í(abs˘ xÍ) ˇessential procedure
ÍAbsˇ returns the magnitude of its argument.
Í (abs -7) ==> 7ˇ
Í(quotient˘ n¯1˘ n¯2Í) ˇessential procedure
Í(remainder˘ n¯1˘ n¯2Í) ˇessential procedure
Í(modulo˘ n¯1˘ n¯2Í) ˇessential procedure
These procedures implement number-theoretic (integer) division: For positive integers ˘n¯1ˇ
and ˘n¯2ˇ, if ˘n¯3ˇ and ˘n¯4ˇ are integers such that ˘n¯1ˇ=˘n¯2˘n¯3ˇ+˘n¯4ˇ and 0 <= ˘n¯4ˇ < ˘n¯2ˇ, then
Í (quotient ˘n¯1Í ˘n¯2Í) ==> ˘n¯3Í
Í (remainder ˘n¯1Í ˘n¯2Í) ==> ˘n¯4Í
Í (modulo ˘n¯1Í ˘n¯2Í) ==> ˘n¯4ˇ
For integers ˘n¯1ˇ and ˘n¯2ˇ with ˘n¯2ˇ not equal to 0,
Í (= ˘n¯1Í (+ (* ˘n¯2Í (quotient ˘n¯1Í ˘n¯2Í))
Í (remainder ˘n¯1Í ˘n¯2Í)))
Í ==> #tˇ
provided all numbers involved in that computation are exact.
The value returned by Íquotientˇ always has the sign of the product of its arguments.
ÍRemainderˇ and Ímoduloˇ differ on negative arguments; the Íremainderˇ is either zero or has
the sign of the dividend, while the Ímoduloˇ always has the sign of the divisor:
Í (modulo 13 4) ==> 1
Í (remainder 13 4) ==> 1
Í
Í (modulo -13 4) ==> 3
Í (remainder -13 4) ==> -1
Í
Í (modulo 13 -4) ==> -3
Í (remainder 13 -4) ==> 1
Í
Í (modulo -13 -4) ==> -1
Í (remainder -13 -4) ==> -1
Í
Í (remainder -13 -4.0) ==> -1.0 ; inexactˇ
Í(gcd˘ n¯1˘ ...Í) ˇessential procedure
Í(lcm˘ n¯1˘ ...Í) ˇessential procedure
These procedures return the greatest common divisor or least common multiple of their
arguments. The result is always non-negative.
Í (gcd 32 -36) ==> 4
Í (gcd) ==> 0
Í (lcm 32 -36) ==> 288
Í (lcm 32.0 -36) ==> 288.0 ; inexact
Í (lcm) ==> 1ˇ
Í(numerator˘ qÍ) ˇprocedure
Í(denominator˘ qÍ) ˇprocedure
These procedures return the numerator or denominator of their argument; the result is
computed as if the argument was represented as a fraction in lowest terms. The denominator
is always positive. The denominator of 0 is defined to be 1.
Í (numerator (/ 6 4)) ==> 3
Í (denominator (/ 6 4)) ==> 2
Í (denominator
Í (exact->inexact (/ 6 4))) ==> 2.0ˇ
Í(floor˘ xÍ) ˇessential procedure
Í(ceiling˘ xÍ) ˇessential procedure
Í(truncate˘ xÍ) ˇessential procedure
Í(round˘ xÍ) ˇessential procedure
These procedures return integers. ÍFloorˇ returns the largest integer not larger than ˘xˇ.
ÍCeilingˇ returns the smallest integer not smaller than ˘xˇ. ÍTruncateˇ returns the integer
closest to ˘xˇ whose absolute value is not larger than the absolute value of ˘xˇ. ÍRoundˇ returns
the closest integer to ˘xˇ, rounding to even when ˘xˇ is halfway between two integers.
˘Rationale:ˇ ÍRoundˇ rounds to even for consistency with the default rounding mode specified by
the IEEE floating point standard.
˘Note:ˇ If the argument to one of these procedures is inexact, then the result will also be
inexact. If an exact value is needed, the result should be passed to the Íinexact->exactˇ
procedure.
Í (floor -4.3) ==> -5.0
Í (ceiling -4.3) ==> -4.0
Í (truncate -4.3) ==> -4.0
Í (round -4.3) ==> -4.0
Í
Í (floor 3.5) ==> 3.0
Í (ceiling 3.5) ==> 4.0
Í (truncate 3.5) ==> 3.0
Í (round 3.5) ==> 4.0 ; inexact
Í
Í (round 7/2) ==> 4 ; exact
Í (round 7) ==> 7ˇ
Í(rationalize˘ x yÍ) ˇprocedure
ÍRationalizeˇ returns the ˘simplestˇ rational number differing from ˘xˇ by no more than ˘yˇ. A
rational number ˘r¯1ˇ is ˘simplerˇ than another rational number ˘r¯2ˇ if ˘r¯1ˇ = ˘p¯1ˇ/˘q¯1ˇ and ˘r¯2ˇ = ˘p¯2ˇ/˘q¯2ˇ
(in lowest terms) and |˘p¯1ˇ| <= |˘p¯2ˇ| and |˘q¯1ˇ| <= |˘q¯2ˇ|. Thus 3/5 is simpler than 4/7. Although not
all rationals are comparable in this ordering (consider 2/7 and 3/5) any interval contains a
rational number that is simpler than every other rational number in that interval (the
simpler 2/5 lies between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of all.
Í (rationalize
Í (inexact->exact .3) 1/10) ==> 1/3 ; exact
Í (rationalize .3 1/10) ==> #i1/3 ; inexactˇ
Í(exp˘ zÍ) ˇprocedure
Í(log˘ zÍ) ˇprocedure
Í(sin˘ zÍ) ˇprocedure
Í(cos˘ zÍ) ˇprocedure
Í(tan˘ zÍ) ˇprocedure
Í(asin˘ zÍ) ˇprocedure
Í(acos˘ zÍ) ˇprocedure
Í(atan˘ zÍ) ˇprocedure
Í(atan˘ y xÍ) ˇprocedure
These procedures are part of every implementation that supports general real numbers; they
compute the usual transcendental functions. ÍLogˇ computes the natural logarithm of ˘zˇ (not the
base ten logarithm). ÍAsinˇ, Íacosˇ, and Íatanˇ compute arcsine (sin˝-1ˇ), arccosine (cos˝-1ˇ), and
arctangent (tan˝-1ˇ), respectively. The two-argument variant of Íatanˇ computes Í(angle
Í(make-rectangular ˘xÍ ˘yÍ))ˇ (see below), even in implementations that don't support
general complex numbers.
In general, the mathematical functions log, arcsine, arccosine, and arctangent are multiply
defined. For nonzero real ˘xˇ, the value of log ˘xˇ is defined to be the one whose imaginary part
lies in the range -π (exclusive) to π (inclusive). log 0 is undefined. The value of log ˘zˇ when ˘zˇ
is complex is defined according to the formula
log ˘zˇ = log magnitude(˘zˇ) + ˘iˇ angle(˘zˇ)
With log defined this way, the values of sin˝-1ˇ ˘zˇ, cos˝-1ˇ ˘zˇ, and tan˝-1ˇ ˘zˇ are according to the
following formulae:
sin˝-1ˇ ˘zˇ = -˘iˇ log(˘izˇ + (1 - ˘z˜2ˇ)˝.5ˇ)
cos˝-1ˇ ˘zˇ = π/2 - sin˝-1ˇ ˘zˇ
tan˝-1ˇ ˘zˇ = (log (1 + ˘izˇ) - log (1-˘izˇ)) / (2˘iˇ)
The above specification follows [CLtL], which in turn cites [Penfield]; refer to these sources
for more detailed discussion of branch cuts, boundary conditions, and implementation of
these functions. When it is possible these procedures produce a real result from a real
argument.
Í(sqrt˘ zÍ) ˇprocedure
Returns the principal square root of ˘zˇ. The result will have either positive real part, or zero
real part and non-negative imaginary part.
Í(expt˘ z¯1˘ z¯2Í) ˇprocedure
Returns ˘z¯1ˇ raised to the power ˘z¯2ˇ:
z1˝z2ˇ = e˝z2 log z1ˇ
0˝0ˇ is defined to be equal to 1.
Í(make-rectangular˘ x¯1˘ x¯2Í) ˇprocedure
Í(make-polar˘ x¯3˘ x¯4Í) ˇprocedure
Í(real-part˘ zÍ) ˇprocedure
Í(imag-part˘ zÍ) ˇprocedure
Í(magnitude˘ zÍ) ˇprocedure
Í(angle˘ zÍ) ˇprocedure
These procedures are part of every implementation that supports general complex numbers.
Suppose ˘x¯1ˇ, ˘x¯2ˇ, ˘x¯3ˇ, and ˘x¯4ˇ are real numbers and ˘zˇ is a complex number such that
˘zˇ = ˘x¯1ˇ + ˘x¯2˘iˇ = ˘x¯3ˇ . e˝i x4ˇ
Then Ímake-rectangularˇ and Ímake-polarˇ return ˘zˇ, Íreal-partˇ returns ˘x¯1ˇ, Íimag-partˇ
returns ˘x¯2ˇ, Ímagnitudeˇ returns ˘x¯3ˇ, and Íangleˇ returns ˘x¯4ˇ. In the case of Íangleˇ, whose
value is not uniquely determined by the preceding rule, the value returned will be the one in
the range -π (exclusive) to π (inclusive).
˘Rationale:ˇ ÍMagnitudeˇ is the same as Íabsˇ for a real argument, but Íabsˇ must be present in
all implementations, whereas Ímagnitudeˇ need only be present in implementations that
support general complex numbers.
Í(exact->inexact˘ zÍ) ˇprocedure
Í(inexact->exact˘ zÍ) ˇprocedure
ÍExact->inexactˇ returns an inexact representation of ˘zˇ. The value returned is the inexact
number that is numerically closest to the argument. If an exact argument has no reasonably
close inexact equivalent, then a violation of an implementation restriction may be reported.
ÍInexact->exactˇ returns an exact representation of ˘zˇ. The value returned is the exact
number that is numerically closest to the argument. If an inexact argument has no reasonably
close exact equivalent, then a violation of an implementation restriction may be reported.
These procedures implement the natural one-to-one correspondence between exact and
inexact integers throughout an implementation-dependent range. See section 6.5.3.
¸6.5.6. Numerical input and outputˇ
Í(number->string˘ numberÍ) ˇessential procedure
Í(number->string˘ number radixÍ) ˇessential procedure
˘Radixˇ must be an exact integer, either 2, 8, 10, or 16. If omitted, ˘radixˇ defaults to 10. The
procedure Ínumber->stringˇ takes a number and a radix and returns as a string an external
representation of the given number in the given radix such that
Í (let ((number ˘numberÍ)
Í (radix ˘radixÍ))
Í (eqv? number
Í (string->number (number->string number
Í radix)
Í radix)))
͡is true. It is an error if no possible result makes this expression true.
If ˘numberˇ is inexact, the radix is 10, and the above expression can be satisfied by a result
that contains a decimal point, then the result contains a decimal point and is expressed using
the minimum number of digits (exclusive of exponent and trailing zeroes) needed to make the
above expression true [howtoprint] [howtoread]; otherwise the format of the result is
unspecified.
The result returned by Ínumber->stringˇ never contains an explicit radix prefix.
˘Note:ˇ The error case can occur only when ˘numberˇ is not a complex number or is a complex
number with a non-rational real or imaginary part.
˘Rationale:ˇ If ˘numberˇ is an inexact number represented using flonums, and the radix is 10,
then the above expression is normally satisfied by a result containing a decimal point. The
unspecified case allows for infinities, NaNs, and non-flonum representations.
Í(string->number˘ stringÍ) ˇessential procedure
Í(string->number˘ string radixÍ) ˇessential procedure
Returns a number of the maximally precise representation expressed by the given ˘stringˇ.
˘Radixˇ must be an exact integer, either 2, 8, 10, or 16. If supplied, ˘radixˇ is a default radix
that may be overridden by an explicit radix prefix in ˘stringˇ (e.g. Í"#o177"ˇ). If ˘radixˇ is not
supplied, then the default radix is 10. If ˘stringˇ is not a syntactically valid notation for a
number, then Ístring->numberˇ returns Í#fˇ.
Í (string->number "100") ==> 100
Í (string->number "100" 16) ==> 256
Í (string->number "1e2") ==> 100.0
Í (string->number "15##") ==> 1500.0ˇ
˘Note:ˇ Although Ístring->numberˇ is an essential procedure, an implementation may restrict
its domain in the following ways. ÍString->numberˇ is permitted to return Í#fˇ whenever
˘stringˇ contains an explicit radix prefix. If all numbers supported by an implementation are
real, then Ístring->numberˇ is permitted to return Í#fˇ whenever ˘stringˇ uses the polar or
rectangular notations for complex numbers. If all numbers are integers, then
Ístring->numberˇ may return Í#fˇ whenever the fractional notation is used. If all numbers
are exact, then Ístring->numberˇ may return Í#fˇ whenever an exponent marker or explicit
exactness prefix is used, or if a Í#ˇ appears in place of a digit. If all inexact numbers are
integers, then Ístring->numberˇ may return Í#fˇ whenever a decimal point is used.
Û6.6. Charactersˇ
Characters are objects that represent printed characters such as letters and digits.
Characters are written using the notation Í#\ˇ<character> or Í#\ˇ<character name>. For
example:
Í#\a ˇ; lower case letter
Í#\A ˇ; upper case letter
Í#\( ˇ; left parenthesis
Í#\ ˇ; the space character
Í#\space ˇ; the preferred way to write a space
Í#\newline ˇ; the newline character
Case is significant in Í#\ˇ<character>, but not in Í#\ˇ<character name>. If <character> in
Í#\ˇ<character> is alphabetic, then the character following <character> must be a delimiter
character such as a space or parenthesis. This rule resolves the ambiguous case where, for
example, the sequence of characters ``Í#\spaceˇ'' could be taken to be either a representation
of the space character or a representation of the character ``Í#\sˇ'' followed by a
representation of the symbol ``Ípaceˇ.''
Characters written in the Í#\ˇ notation are self-evaluating. That is, they do not have to be
quoted in programs.
Some of the procedures that operate on characters ignore the difference between upper case
and lower case. The procedures that ignore case have ``Í-ciˇ'' (for ``case insensitive'')
embedded in their names.
Í(char?˘ objÍ) ˇessential procedure
Returns Í#tˇ if ˘objˇ is a character, otherwise returns Í#fˇ.
Í(char=?˘ char¯1˘ char¯2Í) ˇessential procedure
Í(char<?˘ char¯1˘ char¯2Í) ˇessential procedure
Í(char>?˘ char¯1˘ char¯2Í) ˇessential procedure
Í(char<=?˘ char¯1˘ char¯2Í) ˇessential procedure
Í(char>=?˘ char¯1˘ char¯2Í) ˇessential procedure
These procedures impose a total ordering on the set of characters. It is guaranteed that
under this ordering:
• The upper case characters are in order. For example, Í(char<? #\A #\B)ˇ returns Í#tˇ.
• The lower case characters are in order. For example, Í(char<? #\a #\b)ˇ returns Í#tˇ.
• The digits are in order. For example, Í(char<? #\0 #\9)ˇ returns Í#tˇ.
• Either all the digits precede all the upper case letters, or vice versa.
• Either all the digits precede all the lower case letters, or vice versa.
Some implementations may generalize these procedures to take more than two arguments, as
with the corresponding numerical predicates.
Í(char-ci=?˘ char¯1˘ char¯2Í) ˇessential procedure
Í(char-ci<?˘ char¯1˘ char¯2Í) ˇessential procedure
Í(char-ci>?˘ char¯1˘ char¯2Í) ˇessential procedure
Í(char-ci<=?˘ char¯1˘ char¯2Í) ˇessential procedure
Í(char-ci>=?˘ char¯1˘ char¯2Í) ˇessential procedure
These procedures are similar to Íchar=?ˇ et cetera, but they treat upper case and lower case
letters as the same. For example, Í(char-ci=? #\A #\a)ˇ returns Í#tˇ. Some
implementations may generalize these procedures to take more than two arguments, as with
the corresponding numerical predicates.
Í(char-alphabetic?˘ charÍ) ˇessential procedure
Í(char-numeric?˘ charÍ) ˇessential procedure
Í(char-whitespace?˘ charÍ) ˇessential procedure
Í(char-upper-case?˘ letterÍ) ˇessential procedure
Í(char-lower-case?˘ letterÍ) ˇessential procedure
These procedures return Í#tˇ if their arguments are alphabetic, numeric, whitespace, upper
case, or lower case characters, respectively, otherwise they return Í#fˇ. The following
remarks, which are specific to the ASCII character set, are intended only as a guide: The
alphabetic characters are the 52 upper and lower case letters. The numeric characters are
the ten decimal digits. The whitespace characters are space, tab, line feed, form feed, and
carriage return.
Í(char->integer˘ charÍ) ˇessential procedure
Í(integer->char˘ nÍ) ˇessential procedure
Given a character, Íchar->integerˇ returns an exact integer representation of the
character. Given an exact integer that is the image of a character under Íchar->integerˇ,
Íinteger->charˇ returns that character. These procedures implement injective order
isomorphisms between the set of characters under the Íchar<=?ˇ ordering and some subset of
the integers under the Í<=ˇ ordering. That is, if
Í (char<=? ˘aÍ ˘bÍ) ==> #t and (<= ˘xÍ ˘yÍ) ==> #tˇ
and ˘xˇ and ˘yˇ are in the domain of Íinteger->charˇ, then
Í (<= (char->integer ˘aÍ)
Í (char->integer ˘bÍ)) ==> #t
Í
Í (char<=? (integer->char ˘xÍ)
Í (integer->char ˘yÍ)) ==> #tˇ
Í(char-upcase˘ charÍ) ˇessential procedure
Í(char-downcase˘ charÍ) ˇessential procedure
These procedures return a character ˘char¯2ˇ such that Í(char-ci=? ˘charÍ ˘char¯2Í)ˇ. In
addition, if ˘charˇ is alphabetic, then the result of Íchar-upcaseˇ is upper case and the result
of Íchar-downcaseˇ is lower case.
Û6.7. Stringsˇ
Strings are sequences of characters. Strings are written as sequences of characters
enclosed within doublequotes (Í"ˇ). A doublequote can be written inside a string only by
escaping it with a backslash (Í\ˇ), as in
Í "The word \"recursion\" has many meanings."ˇ
A backslash can be written inside a string only by escaping it with another backslash.
Scheme does not specify the effect of a backslash within a string that is not followed by a
doublequote or backslash.
A string constant may continue from one line to the next, but the exact contents of such a
string are unspecified.
The ˘lengthˇ of a string is the number of characters that it contains. This number is a
non-negative integer that is fixed when the string is created. The ˘valid indexesˇ of a string
are the exact non-negative integers less than the length of the string. The first character of
a string has index 0, the second has index 1, and so on.
In phrases such as ``the characters of ˘stringˇ beginning with index ˘startˇ and ending with index
˘endˇ,'' it is understood that the index ˘startˇ is inclusive and the index ˘endˇ is exclusive. Thus if
˘startˇ and ˘endˇ are the same index, a null substring is referred to, and if ˘startˇ is zero and ˘endˇ
is the length of ˘stringˇ, then the entire string is referred to.
Some of the procedures that operate on strings ignore the difference between upper and
lower case. The versions that ignore case have ``Í-ciˇ'' (for ``case insensitive'') embedded in
their names.
Í(string?˘ objÍ) ˇessential procedure
Returns Í#tˇ if ˘objˇ is a string, otherwise returns Í#fˇ.
Í(make-string˘ kÍ) ˇessential procedure
Í(make-string˘ k charÍ) ˇessential procedure
ÍMake-stringˇ returns a newly allocated string of length ˘kˇ. If ˘charˇ is given, then all
elements of the string are initialized to ˘charˇ, otherwise the contents of the ˘stringˇ are
unspecified.
Í(string˘ char ...Í) ˇessential procedure
Returns a newly allocated string composed of the arguments.
Í(string-length˘ stringÍ) ˇessential procedure
Returns the number of characters in the given ˘stringˇ.
Í(string-ref˘ string kÍ) ˇessential procedure
˘kˇ must be a valid index of ˘stringˇ. ÍString-refˇ returns character ˘kˇ of ˘stringˇ using
zero-origin indexing.
Í(string-set!˘ string k charÍ) ˇessential procedure
˘kˇ must be a valid index of ˘stringˇ. ÍString-set!ˇ stores ˘charˇ in element ˘kˇ of ˘stringˇ and
returns an unspecified value.
Í (define (f) (make-string 3 #\*))
Í (define (g) "***")
Í (string-set! (f) 0 #\?) ==> ˘unspecifiedÍ
Í (string-set! (g) 0 #\?) ==> ˘errorÍ
Í (string-set! (symbol->string 'immutable)
Í 0
Í #\?) ==> ˘errorˇ
Í(string=?˘ string¯1˘ string¯2Í) ˇessential procedure
Í(string-ci=?˘ string¯1˘ string¯2Í) ˇessential procedure
Returns Í#tˇ if the two strings are the same length and contain the same characters in the
same positions, otherwise returns Í#fˇ. ÍString-ci=?ˇ treats upper and lower case letters as
though they were the same character, but Ístring=?ˇ treats upper and lower case as distinct
characters.
Í(string<?˘ string¯1˘ string¯2Í) ˇessential procedure
Í(string>?˘ string¯1˘ string¯2Í) ˇessential procedure
Í(string<=?˘ string¯1˘ string¯2Í) ˇessential procedure
Í(string>=?˘ string¯1˘ string¯2Í) ˇessential procedure
Í(string-ci<?˘ string¯1˘ string¯2Í) ˇessential procedure
Í(string-ci>?˘ string¯1˘ string¯2Í) ˇessential procedure
Í(string-ci<=?˘ string¯1˘ string¯2Í) ˇessential procedure
Í(string-ci>=?˘ string¯1˘ string¯2Í) ˇessential procedure
These procedures are the lexicographic extensions to strings of the corresponding orderings
on characters. For example, Ístring<?ˇ is the lexicographic ordering on strings induced by
the ordering Íchar<?ˇ on characters. If two strings differ in length but are the same up to the
length of the shorter string, the shorter string is considered to be lexicographically less
than the longer string.
Implementations may generalize these and the Ístring=?ˇ and Ístring-ci=?ˇ procedures to
take more than two arguments, as with the corresponding numerical predicates.
Í(substring˘ string start endÍ) ˇessential procedure
˘Stringˇ must be a string, and ˘startˇ and ˘endˇ must be exact integers satisfying
0 <= ˘startˇ <= ˘endˇ <= Í(string-length ˘stringÍ).ˇ
ÍSubstringˇ returns a newly allocated string formed from the characters of ˘stringˇ beginning
with index ˘startˇ (inclusive) and ending with index ˘endˇ (exclusive).
Í(string-append˘ string ...Í) ˇessential procedure
Returns a newly allocated string whose characters form the concatenation of the given
strings.
Í(string->list˘ stringÍ) ˇessential procedure
Í(list->string˘ charsÍ) ˇessential procedure
ÍString->listˇ returns a newly allocated list of the characters that make up the given
string. ÍList->stringˇ returns a newly allocated string formed from the characters in the
list ˘charsˇ. ÍString->listˇ and Ílist->stringˇ are inverses so far as Íequal?ˇ is concerned.
Í(string-copy˘ stringÍ) ˇprocedure
Returns a newly allocated copy of the given ˘stringˇ.
Í(string-fill!˘ string charÍ) ˇprocedure
Stores ˘charˇ in every element of the given ˘stringˇ and returns an unspecified value.
Û6.8. Vectorsˇ
Vectors are heterogenous structures whose elements are indexed by integers. A vector
typically occupies less space than a list of the same length, and the average time required to
access a randomly chosen element is typically less for the vector than for the list.
The ˘lengthˇ of a vector is the number of elements that it contains. This number is a
non-negative integer that is fixed when the vector is created. The ˘valid indexesˇ of a vector
are the exact non-negative integers less than the length of the vector. The first element in a
vector is indexed by zero, and the last element is indexed by one less than the length of the
vector.
Vectors are written using the notation Í#(˘objÍ ...)ˇ. For example, a vector of length 3
containing the number zero in element 0, the list Í(2 2 2 2)ˇ in element 1, and the string
Í"Anna"ˇ in element 2 can be written as following:
Í #(0 (2 2 2 2) "Anna")ˇ
Note that this is the external representation of a vector, not an expression evaluating to a
vector. Like list constants, vector constants must be quoted:
Í '#(0 (2 2 2 2) "Anna")
Í ==> #(0 (2 2 2 2) "Anna")ˇ
Í(vector?˘ objÍ) ˇessential procedure
Returns Í#tˇ if ˘objˇ is a vector, otherwise returns Í#fˇ.
Í(make-vector˘ kÍ) ˇessential procedure
Í(make-vector˘ k fillÍ) ˇprocedure
Returns a newly allocated vector of ˘kˇ elements. If a second argument is given, then each
element is initialized to ˘fillˇ. Otherwise the initial contents of each element is unspecified.
Í(vector˘ obj ...Í) ˇessential procedure
Returns a newly allocated vector whose elements contain the given arguments. Analogous to
Ílistˇ.
Í (vector 'a 'b 'c) ==> #(a b c)ˇ
Í(vector-length˘ vectorÍ) ˇessential procedure
Returns the number of elements in ˘vectorˇ.
Í(vector-ref˘ vector kÍ) ˇessential procedure
˘kˇ must be a valid index of ˘vectorˇ. ÍVector-refˇ returns the contents of element ˘kˇ of ˘vectorˇ.
Í (vector-ref '#(1 1 2 3 5 8 13 21)
Í 5)
Í ==> 8
Í (vector-ref '#(1 1 2 3 5 8 13 21)
Í (inexact->exact
Í (round (* 2 (acos -1)))))
Í ==> 13ˇ
Í(vector-set!˘ vector k objÍ) ˇessential procedure
˘kˇ must be a valid index of ˘vectorˇ. ÍVector-set!ˇ stores ˘objˇ in element ˘kˇ of ˘vectorˇ. The value
returned by Ívector-set!ˇ is unspecified.
Í (let ((vec (vector 0 '(2 2 2 2) "Anna")))
Í (vector-set! vec 1 '("Sue" "Sue"))
Í vec)
Í ==> #(0 ("Sue" "Sue") "Anna")
Í
Í (vector-set! '#(0 1 2) 1 "doe")
Í ==> ˘errorÍ ; constant vectorˇ
Í(vector->list˘ vectorÍ) ˇessential procedure
Í(list->vector˘ listÍ) ˇessential procedure
ÍVector->listˇ returns a newly allocated list of the objects contained in the elements of
˘vectorˇ. ÍList->vectorˇ returns a newly created vector initialized to the elements of the list
˘listˇ.
Í (vector->list '#(dah dah didah))
Í ==> (dah dah didah)
Í (list->vector '(dididit dah))
Í ==> #(dididit dah)ˇ
Í(vector-fill!˘ vector fillÍ) ˇprocedure
Stores ˘fillˇ in every element of ˘vectorˇ. The value returned by Ívector-fill!ˇ is unspecified.
Û6.9. Control featuresˇ
This chapter describes various primitive procedures which control the flow of program
execution in special ways. The Íprocedure?ˇ predicate is also described here.
Í(procedure?˘ objÍ) ˇessential procedure
Returns Í#tˇ if ˘objˇ is a procedure, otherwise returns Í#fˇ.
Í (procedure? car) ==> #t
Í (procedure? 'car) ==> #f
Í (procedure? (lambda (x) (* x x)))
Í ==> #t
Í (procedure? '(lambda (x) (* x x)))
Í ==> #f
Í (call-with-current-continuation procedure?)
Í ==> #tˇ
Í(apply˘ proc argsÍ) ˇessential procedure
Í(apply˘ proc arg¯1˘ ... argsÍ) ˇprocedure
˘Procˇ must be a procedure and ˘argsˇ must be a list. The first (essential) form calls ˘procˇ with
the elements of ˘argsˇ as the actual arguments. The second form is a generalization of the first
that calls ˘procˇ with the elements of the list Í(append (list ˘arg¯1Í ...) ˘argsÍ)ˇ as the
actual arguments.
Í (apply + (list 3 4)) ==> 7
Í
Í (define compose
Í (lambda (f g)
Í (lambda args
Í (f (apply g args)))))
Í
Í ((compose sqrt *) 12 75) ==> 30ˇ
Í(map˘ proc list¯1˘ list¯2˘ ...Í) ˇessential procedure
The ˘listˇs must be lists, and ˘procˇ must be a procedure taking as many arguments as there are
˘listˇs. If more than one ˘listˇ is given, then they must all be the same length. ÍMapˇ applies ˘procˇ
element-wise to the elements of the ˘listˇs and returns a list of the results, in order from left
to right. The dynamic order in which ˘procˇ is applied to the elements of the ˘listˇs is
unspecified.
Í (map cadr '((a b) (d e) (g h)))
Í ==> (b e h)
Í
Í (map (lambda (n) (expt n n))
Í '(1 2 3 4 5))
Í ==> (1 4 27 256 3125)
Í
Í (map + '(1 2 3) '(4 5 6)) ==> (5 7 9)
Í
Í (let ((count 0))
Í (map (lambda (ignored)
Í (set! count (+ count 1))
Í count)
Í '(a b c))) ==> ˘unspecifiedˇ
Í(for-each˘ proc list¯1˘ list¯2˘ ...Í) ˇessential procedure
The arguments to Ífor-eachˇ are like the arguments to Ímapˇ, but Ífor-eachˇ calls ˘procˇ for its
side effects rather than for its values. Unlike Ímapˇ, Ífor-eachˇ is guaranteed to call ˘procˇ on
the elements of the ˘listˇs in order from the first element to the last, and the value returned
by Ífor-eachˇ is unspecified.
Í (let ((v (make-vector 5)))
Í (for-each (lambda (i)
Í (vector-set! v i (* i i)))
Í '(0 1 2 3 4))
Í v) ==> #(0 1 4 9 16)ˇ
Í(force˘ promiseÍ) ˇprocedure
Forces the value of ˘promiseˇ (see Ídelayˇ, section 4.2.5). If no value has been computed for
the promise, then a value is computed and returned. The value of the promise is cached (or
``memoized'') so that if it is forced a second time, the previously computed value is
returned.
Í (force (delay (+ 1 2))) ==> 3
Í (let ((p (delay (+ 1 2))))
Í (list (force p) (force p)))
Í ==> (3 3)
Í
Í (define a-stream
Í (letrec ((next
Í (lambda (n)
Í (cons n (delay (next (+ n 1)))))))
Í (next 0)))
Í (define head car)
Í (define tail
Í (lambda (stream) (force (cdr stream))))
Í
Í (head (tail (tail a-stream)))
Í ==> 2ˇ
ÍForceˇ and Ídelayˇ are mainly intended for programs written in functional style. The
following examples should not be considered to illustrate good programming style, but they
illustrate the property that only one value is computed for a promise, no matter how many
times it is forced.
Í (define count 0)
Í (define p
Í (delay (begin (set! count (+ count 1))
Í (if (> count x)
Í count
Í (force p)))))
Í (define x 5)
Í p ==> ˘a promiseÍ
Í (force p) ==> 6
Í p ==> ˘a promise, stillÍ
Í (begin (set! x 10)
Í (force p)) ==> 6ˇ
Here is a possible implementation of Ídelayˇ and Íforceˇ. Promises are implemented here as
procedures of no arguments, and Íforceˇ simply calls its argument:
Í (define force
Í (lambda (object)
Í (object)))ˇ
We define the expression
Í (delay ˇ<expression>Í)ˇ
to have the same meaning as the procedure call
Í (make-promise (lambda () ˇ<expression>Í)),ˇ
where Ímake-promiseˇ is defined as follows:
Í (define make-promise
Í (lambda (proc)
Í (let ((result-ready? #f)
Í (result #f))
Í (lambda ()
Í (if result-ready?
Í result
Í (let ((x (proc)))
Í (if result-ready?
Í result
Í (begin (set! result-ready? #t)
Í (set! result x)
Í result))))))))ˇ
˘Rationale:ˇ A promise may refer to its own value, as in the last example above. Forcing such
a promise may cause the promise to be forced a second time before the value of the first
force has been computed. This complicates the definition of Ímake-promiseˇ.
Various extensions to this semantics of Ídelayˇ and Íforceˇ are supported in some
implementations:
• Calling Íforceˇ on an object that is not a promise may simply return the object.
• It may be the case that there is no means by which a promise can be operationally
distinguished from its forced value. That is, expressions like the following may evaluate to
either Í#tˇ or to Í#fˇ, depending on the implementation:
Í (eqv? (delay 1) 1) ==> ˘unspecifiedÍ
Í (pair? (delay (cons 1 2))) ==> ˘unspecifiedˇ
• Some implementations may implement ``implicit forcing,'' where the value of a promise is
forced by primitive procedures like Ícdrˇ and Í+ˇ:
Í (+ (delay (* 3 7)) 13) ==> 34ˇ
Í(call-with-current-continuation˘ procÍ) ˇessential procedure
˘Procˇ must be a procedure of one argument. The procedure
Ícall-with-current-continuationˇ packages up the current continuation (see the
rationale below) as an ``escape procedure'' and passes it as an argument to ˘procˇ. The escape
procedure is a Scheme procedure of one argument that, if it is later passed a value, will
ignore whatever continuation is in effect at that later time and will give the value instead to
the continuation that was in effect when the escape procedure was created.
The escape procedure that is passed to ˘procˇ has unlimited extent just like any other
procedure in Scheme. It may be stored in variables or data structures and may be called as
many times as desired.
The following examples show only the most common uses of
Ícall-with-current-continuationˇ. If all real programs were as simple as these
examples, there would be no need for a procedure with the power of
Ícall-with-current-continuationˇ.
Í (call-with-current-continuation
Í (lambda (exit)
Í (for-each (lambda (x)
Í (if (negative? x)
Í (exit x)))
Í '(54 0 37 -3 245 19))
Í #t)) ==> -3
Í
Í (define list-length
Í (lambda (obj)
Í (call-with-current-continuation
Í (lambda (return)
Í (letrec ((r
Í (lambda (obj)
Í (cond ((null? obj) 0)
Í ((pair? obj)
Í (+ (r (cdr obj)) 1))
Í (else (return #f))))))
Í (r obj))))))
Í
Í (list-length '(1 2 3 4)) ==> 4
Í
Í (list-length '(a b . c)) ==> #fˇ
˘Rationale:ˇ
A common use of Ícall-with-current-continuationˇ is for structured, non-local exits
from loops or procedure bodies, but in fact Ícall-with-current-continuationˇ is
extremely useful for implementing a wide variety of advanced control structures.
Whenever a Scheme expression is evaluated there is a ˘continuationˇ wanting the result of the
expression. The continuation represents an entire (default) future for the computation. If the
expression is evaluated at top level, for example, then the continuation might take the
result, print it on the screen, prompt for the next input, evaluate it, and so on forever. Most
of the time the continuation includes actions specified by user code, as in a continuation that
will take the result, multiply it by the value stored in a local variable, add seven, and give
the answer to the top level continuation to be printed. Normally these ubiquitous
continuations are hidden behind the scenes and programmers don't think much about them. On
rare occasions, however, a programmer may need to deal with continuations explicitly.
ÍCall-with-current-continuationˇ allows Scheme programmers to do that by creating
a procedure that acts just like the current continuation.
Most programming languages incorporate one or more special-purpose escape constructs
with names like Íexitˇ, Íreturnˇ, or even Ígotoˇ. In 1965, however, Peter Landin [Landin]
invented a general purpose escape operator called the J-operator. John Reynolds [Reynolds]
described a simpler but equally powerful construct in 1972. The Ícatchˇ special form
described by Sussman and Steele in the 1975 report on Scheme is exactly the same as
Reynolds's construct, though its name came from a less general construct in MacLisp.
Several Scheme implementors noticed that the full power of the Ícatchˇ construct could be
provided by a procedure instead of by a special syntactic construct, and the name
Ícall-with-current-continuationˇ was coined in 1982. This name is descriptive, but
opinions differ on the merits of such a long name, and some people use the name Ícall/ccˇ
instead.
Û6.10. Input and outputˇ
¸6.10.1. Portsˇ
Ports represent input and output devices. To Scheme, an input port is a Scheme object that
can deliver characters upon command, while an output port is a Scheme object that can
accept characters.
Í(call-with-input-file˘ string procÍ) ˇessential procedure
Í(call-with-output-file˘ string procÍ) ˇessential procedure
˘Procˇ should be a procedure of one argument, and ˘stringˇ should be a string naming a file. For
Ícall-with-input-fileˇ, the file must already exist; for Ícall-with-output-fileˇ, the
effect is unspecified if the file already exists. These procedures call ˘procˇ with one
argument: the port obtained by opening the named file for input or output. If the file cannot be
opened, an error is signalled. If the procedure returns, then the port is closed automatically
and the value yielded by the procedure is returned. If the procedure does not return, then the
port will not be closed automatically unless it is possible to prove that the port will never
again be used for a read or write operation.
˘Rationale:ˇ Because Scheme's escape procedures have unlimited extent, it is possible to
escape from the current continuation but later to escape back in. If implementations were
permitted to close the port on any escape from the current continuation, then it would be
impossible to write portable code using both Ícall-with-current-continuationˇ and
Ícall-with-input-fileˇ or Ícall-with-output-fileˇ.
Í(input-port?˘ objÍ) ˇessential procedure
Í(output-port?˘ objÍ) ˇessential procedure
Returns Í#tˇ if ˘objˇ is an input port or output port respectively, otherwise returns Í#fˇ.
Í(current-input-port) ˇessential procedure
Í(current-output-port) ˇessential procedure
Returns the current default input or output port.
Í(with-input-from-file˘ string thunkÍ) ˇprocedure
Í(with-output-to-file˘ string thunkÍ) ˇprocedure
˘Thunkˇ must be a procedure of no arguments, and ˘stringˇ must be a string naming a file. For
Íwith-input-from-fileˇ, the file must already exist; for Íwith-output-to-fileˇ, the
effect is unspecified if the file already exists. The file is opened for input or output, an input
or output port connected to it is made the default value returned by Ícurrent-input-portˇ
or Ícurrent-output-portˇ, and the ˘thunkˇ is called with no arguments. When the ˘thunkˇ
returns, the port is closed and the previous default is restored. ÍWith-input-from-fileˇ
and Íwith-output-to-fileˇ return the value yielded by ˘thunkˇ. If an escape procedure is
used to escape from the continuation of these procedures, their behavior is implementation
dependent.
Í(open-input-file˘ filenameÍ) ˇessential procedure
Takes a string naming an existing file and returns an input port capable of delivering
characters from the file. If the file cannot be opened, an error is signalled.
Í(open-output-file˘ filenameÍ) ˇessential procedure
Takes a string naming an output file to be created and returns an output port capable of
writing characters to a new file by that name. If the file cannot be opened, an error is
signalled. If a file with the given name already exists, the effect is unspecified.
Í(close-input-port˘ portÍ) ˇessential procedure
Í(close-output-port˘ portÍ) ˇessential procedure
Closes the file associated with ˘portˇ, rendering the ˘portˇ incapable of delivering or accepting
characters. These routines have no effect if the file has already been closed. The value
returned is unspecified.
¸6.10.2. Inputˇ
Í(read) ˇessential procedure
Í(read˘ portÍ) ˇessential procedure
ÍReadˇ converts external representations of Scheme objects into the objects themselves. That
is, it is a parser for the nonterminal <datum> (see sections 7.1.2 and 6.3). ÍReadˇ returns the
next object parsable from the given input ˘portˇ, updating ˘portˇ to point to the first character
past the end of the external representation of the object.
If an end of file is encountered in the input before any characters are found that can begin an
object, then an end of file object is returned. The port remains open, and further attempts to
read will also return an end of file object. If an end of file is encountered after the beginning
of an object's external representation, but the external representation is incomplete and
therefore not parsable, an error is signalled.
The ˘portˇ argument may be omitted, in which case it defaults to the value returned by
Ícurrent-input-portˇ. It is an error to read from a closed port.
Í(read-char) ˇessential procedure
Í(read-char˘ portÍ) ˇessential procedure
Returns the next character available from the input ˘portˇ, updating the ˘portˇ to point to the
following character. If no more characters are available, an end of file object is returned.
˘Portˇ may be omitted, in which case it defaults to the value returned by
Ícurrent-input-portˇ.
Í(peek-char) ˇessential procedure
Í(peek-char˘ portÍ) ˇessential procedure
Returns the next character available from the input ˘portˇ, ˘withoutˇ updating the ˘portˇ to point
to the following character. If no more characters are available, an end of file object is
returned. ˘Portˇ may be omitted, in which case it defaults to the value returned by
Ícurrent-input-portˇ.
˘Note:ˇ The value returned by a call to Ípeek-charˇ is the same as the value that would have
been returned by a call to Íread-charˇ with the same ˘portˇ. The only difference is that the
very next call to Íread-charˇ or Ípeek-charˇ on that ˘portˇ will return the value returned by
the preceding call to Ípeek-charˇ. In particular, a call to Ípeek-charˇ on an interactive port
will hang waiting for input whenever a call to Íread-charˇ would have hung.
Í(eof-object?˘ objÍ) ˇessential procedure
Returns Í#tˇ if ˘objˇ is an end of file object, otherwise returns Í#fˇ. The precise set of end of file
objects will vary among implementations, but in any case no end of file object will ever be
an object that can be read in using Íreadˇ.
Í(char-ready?) ˇprocedure
Í(char-ready?˘ portÍ) ˇprocedure
Returns Í#tˇ if a character is ready on the input ˘portˇ and returns Í#fˇ otherwise. If
Íchar-readyˇ returns Í#tˇ then the next Íread-charˇ operation on the given ˘portˇ is guaranteed
not to hang. If the ˘portˇ is at end of file then Íchar-ready?ˇ returns Í#tˇ. ˘Portˇ may be omitted,
in which case it defaults to the value returned by Ícurrent-input-portˇ.
˘Rationale:ˇ ÍChar-ready?ˇ exists to make it possible for a program to accept characters from
interactive ports without getting stuck waiting for input. Any input editors associated with
such ports must ensure that characters whose existence has been asserted by
Íchar-ready?ˇ cannot be rubbed out. If Íchar-ready?ˇ were to return Í#fˇ at end of file, a
port at end of file would be indistinguishable from an interactive port that has no ready
characters.
¸6.10.3. Outputˇ
Í(write˘ objÍ) ˇessential procedure
Í(write˘ obj portÍ) ˇessential procedure
Writes a written representation of ˘objˇ to the given ˘portˇ. Strings that appear in the written
representation are enclosed in doublequotes, and within those strings backslash and
doublequote characters are escaped by backslashes. ÍWriteˇ returns an unspecified value. The
˘portˇ argument may be omitted, in which case it defaults to the value returned by
Ícurrent-output-portˇ.
Í(display˘ objÍ) ˇessential procedure
Í(display˘ obj portÍ) ˇessential procedure
Writes a representation of ˘objˇ to the given ˘portˇ. Strings that appear in the written
representation are not enclosed in doublequotes, and no characters are escaped within those
strings. Character objects appear in the representation as if written by Íwrite-charˇ
instead of by Íwriteˇ. ÍDisplayˇ returns an unspecified value. The ˘portˇ argument may be
omitted, in which case it defaults to the value returned by Ícurrent-output-portˇ.
˘Rationale:ˇ ÍWriteˇ is intended for producing machine-readable output and Ídisplayˇ is for
producing human-readable output. Implementations that allow ``slashification'' within
symbols will probably want Íwriteˇ but not Ídisplayˇ to slashify funny characters in
symbols.
Í(newline) ˇessential procedure
Í(newline˘ portÍ) ˇessential procedure
Writes an end of line to ˘portˇ. Exactly how this is done differs from one operating system to
another. Returns an unspecified value. The ˘portˇ argument may be omitted, in which case it
defaults to the value returned by Ícurrent-output-portˇ.
Í(write-char˘ charÍ) ˇessential procedure
Í(write-char˘ char portÍ) ˇessential procedure
Writes the character ˘charˇ (not an external representation of the character) to the given ˘portˇ
and returns an unspecified value. The ˘portˇ argument may be omitted, in which case it
defaults to the value returned by Ícurrent-output-portˇ.
¸6.10.4. System interfaceˇ
Questions of system interface generally fall outside of the domain of this report. However,
the following operations are important enough to deserve description here.
Í(load˘ filenameÍ) ˇessential procedure
˘Filenameˇ should be a string naming an existing file containing Scheme source code. The Íloadˇ
procedure reads expressions and definitions from the file and evaluates them sequentially. It
is unspecified whether the results of the expressions are printed. The Íloadˇ procedure does
not affect the values returned by Ícurrent-input-portˇ and Ícurrent-output-portˇ.
ÍLoadˇ returns an unspecified value.
˘Rationale:ˇ For portability, Íloadˇ must operate on source files. Its operation on other kinds of
files necessarily varies among implementations.
Í(transcript-on˘ filenameÍ) ˇprocedure
Í(transcript-off) ˇprocedure
˘Filenameˇ must be a string naming an output file to be created. The effect of Ítranscript-onˇ
is to open the named file for output, and to cause a transcript of subsequent interaction
between the user and the Scheme system to be written to the file. The transcript is ended by
a call to Ítranscript-offˇ, which closes the transcript file. Only one transcript may be in
progress at any time, though some implementations may relax this restriction. The values
returned by these procedures are unspecified.
Û7. Formal syntax and semanticsˇ
Due to formatting restrictions, this chapter is not included in the online help.